Angularjs指令监视绑定属性

问题描述 投票:0回答:1

我需要创建简单的指令,如果另一个值更改,它将显示一些值。例如,它将监视'event',如果event.eventDuration ==='Now',则必须将其值更改为'Surprise!'。

使用我的代码,我只能在控制台中看到一次有效事件。如果我进行了某些更改,则仅{{event.eventDuration}}会更改,而不是我的指令。我做错了什么?

在使用它的html代码中,我有这个:

    <event-time event="event"></event-time>{{event.eventDuration}}

这是我的自定义指令:

angular.module('my-app').directive('eventTime', function ($c, $compile) {
    var linker = function(scope, element, attrs) {
        scope.$watch('event', function(newValue){
            if (newValue !== undefined && newValue.eventDuration !== undefined) {
                scope.value = newValue.eventDuration;
                element.html(scope.value);
                $compile(element.contents())(scope);
            }
        });
    };

    return {
        restrict: 'E',
        template: '{{value}}',
        transclude: true,
        scope: {
            'event': '='
        },
        link: linker,
        controller: function ($scope) {
            //init value
            $scope.value = 'x';
        }
    };
});
angularjs directive watch
1个回答
1
投票

您可以像这样监视一个表达式:

scope.$watch("event.eventDuration", function(v){
   if (v === "Now"){
      // do whatever you need to display "Surprise!"
   }
});

您的问题尚不清楚"Surprise!"字符串应在何处呈现。如果仅是模板中显示的scope.value,则无需执行任何操作。只需分配$compile

© www.soinside.com 2019 - 2024. All rights reserved.