AngularJS 指令检测在模型属性更改中传递

标签 angularjs directive

我有一个独立作用域的指令。我想检测作为父范围变量的属性的更改。

到目前为止,我有以下内容:

var app = angular.module("app", []);


app.controller("ctrl", function($scope, $timeout) {

  $timeout(function() {
    console.log("called");

    $scope.isReady = true;
    $scope.$apply();
  }, 2000);


});

app.directive("car", function($log) {
  return {
    scope: {
      make: "=carMake"
    },
    restrict: 'E',
    template: "<strong ng-bind='make'></strong>",
    link: function(scope, elem, attrs) {

      scope.$watch(attrs.shouldDo, function(value) {
        var val = value || null;
        if (val) {
          $log.info(scope.$eval(attrs.shouldDo));
        }
      }, true);

    }
  }
});

http://fiddle.jshell.net/8Qhuk/

如果我将作用域设置为 false 它会起作用,但是我需要它来处理一个独立的作用域。

最佳答案

只需将 scope 部分写成:

 scope: {
        make : "=carMake",
        shouldDo: '='
    },

修复演示 Fiddle

指令示例:

app.directive("car", function($log) {
    return {
        scope: {
            make: "=carMake",
            shouldDo: '='
        },
        restrict: 'E',
        template: "<strong ng-bind='make'></strong>",
        link: function(scope, elem, attrs) {    

            scope.$watch(function() {
                return scope.shouldDo
            },
            function(newValue, oldValue) {
                var val = newValue || null;
                if (val) {
                    $log.info(scope.shouldDo);
                }
            });    
        }
    }
});

watch 中,我们只监听一个变量。你不需要 true 标志


顺便说一句,你可以使用绑定(bind)一次只读

 scope: {
        make : "=carMake",
        shouldDo: '@'
    },

当 HTML 时:

<car car-make="make" should-do="{{isReady}}"></car>

演示 2 Fiddle

关于AngularJS 指令检测在模型属性更改中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24883093/

相关文章:

javascript - 如何在 angularjs e2e 测试中使用 isVisible/isElementPresent,抛出错误 "TypeError: Object #<Object> has no method ' isVisible'"

javascript - AngularJS在指令模板中执行 Controller 函数

jquery - Bootstrap selectpicker VueJS 指令

templates - AngularJS - 在自定义指令中渲染模板之前格式化 ng-model

angularjs - 在下拉框中自动选择已保存的值

javascript - firebase + angularjs顺序

javascript - Material Design md-datepicker 在页面加载时自动打开

javascript - Angular js动态生成链接

c# - C#中语句 "to qualify the use of a type in that namespace"是什么意思