首页 > 关于angularjs的$watch的使用,以及父子指令之间获取数据的问题

关于angularjs的$watch的使用,以及父子指令之间获取数据的问题

var app.angular.module('app', []);

app.controller('appController', function($scope) {
    var ctrl = this;
    if(this.currentValue == "") {
        console.log("空字符串");
    }
});

app.directive('appDirective', function() {
    return {
        scope: {},
        bindToController: {
            currentValue: '=?'
        },
        controller: 'appController',
        controllerAs: 'appCtrl',
        link: function(scope, element, attrs, app) {
            if(angular.isUndefined(attrs.currentValue)) {
                scope.currentValue = "";
            }
        }
    }
});

app.directive('myDirective', function() {
    return {
        scope: {},
        controller: function() {},
        controllerAs: 'myCtrl',
        require: '^appDirective'
        link: function(scope, element, attrs, app) {
            
            //我想在这里监听appDirective里的currentValue的值,但是下面这三种写法都不能实现,应该怎么写watch函数呢?
            
            var watch1 = scope.$watch('app.currentValue', function(){});
            
            var watch2 = scope.$watch('appCtrl.currentValue', function(){});
            
            scope.cv = appCtrl.currentValue;
            var watch3 = scope.$watch('cv', function(){});
        }
    }
})
  1. 我想在myDirective里监听appDirective里的值,该怎么写watch函数呢?

  2. 在myDirective的HTML模板里使用appCtrl.currentValue及$parent.currentValue的形式都不能获取该值,是为什么呢?


说说你实际要解决的问题吧,别这么乱写指令了。一个指令里边三个$watch,你这程序跑起来数据稍微多一点就得卡住。另外能不写指令就别写,指令虽然是angular的亮点,但是也是性能上的大坑。


把你的

scope.$watch('app.currentValue', function() { /* something */ });

换成

scope.$watch(function() { return app.currentValue; }, function() {
    /* something */
})

scope.$watch的第一个参数可以是字符串也可以是函数。
为函数时监听其返回值。
为字符串时则是监听在当前scope里执行这个expression的结果

在问题的例子里,两个directive都采用了isolated scope,内部directive无法通过scope原形链访问外部directive的scope内容,所以采用字符串参数的scope.$watch监听不到。

【热门文章】
【热门文章】