【问题标题】:Angularjs directive watching binded attributesAngularjs 指令监视绑定的属性
【发布时间】:2020-02-23 12:44:57
【问题描述】:

我需要创建一个简单的指令,如果另一个值发生变化,它将显示一些值。例如,它将监视“事件”,如果 event.eventDuration === 'Now' 则必须将其值更改为“惊喜!”。

使用我的代码,我只能在控制台中看到一次有效事件。如果我做了一些更改,只有 {{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';
        }
    };
});

【问题讨论】:

  • 您可能想查看event 的属性,而不仅仅是对象:scope.$watch('event', {…}, true);

标签: angularjs directive watch


【解决方案1】:

你可以 $watch 一个表达式,像这样:

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

从您的问题中不清楚应该在哪里呈现 "Surprise!" 字符串。如果它只是您在模板中显示的scope.value,那么您不需要$compile 任何东西。只需分配$scope.value = "Surprise!"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-01
    • 2018-02-11
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    相关资源
    最近更新 更多