当控制器中的值发生变化时,从指令中的控制器访问值

时间:2014-08-06 12:00:58

标签: angularjs angularjs-directive angularjs-scope

我创建了这个jsfiddle来说明我的问题。

http://jsfiddle.net/RmDuw/84/

HTML:     

    <button ng-click="toggleAwesome()">My awsomw button</button>
    <br />
    {{awesome}}
    <br />

    With template: <example-directive1 awesome="awesome">{{message}}</example-directive1>    

    <br />

    Without template: <example-directive2>{{message}}</example-directive2> 
</div>

JS:     var app = angular.module(&#39; myApp&#39;,[]);

function MyCtrl($scope) {
    $scope.message = 'hello';
    $scope.awesome = false;

    $scope.toggleAwesome = function(){
        if($scope.awesome){ $scope.awesome = false; }
        else { $scope.awesome = true; }
    };
}

app.directive('exampleDirective1', function() {
    return {
        restrict: 'E',
        template: '<span></span>',
        replace: true,
        scope: {
            awesome:'='
        },
        link: function(scope, elm, attrs) {
            console.log(scope.awesome);
            scope.$watch(scope.awesome,function(){ console.log(scope.awesome); })                      
        }
    };
});


app.directive('exampleDirective2', function() {
    return {
        restrict: 'E',
        link: function(scope, elm, attrs) {

        }
    };
});

有没有办法知道awesome何时被修改?

2 个答案:

答案 0 :(得分:2)

请看这里http://jsfiddle.net/E32A2/而不是$ watch(scope.awesome .. 使用范围。$ watch('awesome'...

 app.directive('exampleDirective1', function () {
        return {
            restrict: 'E',
            template: '<span> {{awesome}}</span>',
            replace: true,
            scope: {
                awesome: '='
            },
            link: function (scope, elm, attrs) {
                console.log(this.awesome);
                scope.$watch('awesome', function (value) {
                    console.log(value);
                })
            }
        };
    });

答案 1 :(得分:1)

我会将$watch更改为:

  scope.$watch(function(){return scope.awesome;},
           function(newV){
            console.log(newV);
        })  

此声明的优势function(){return scope.awesome;} - 您不必担心拼写问题。我认为将其写为字符串可能会导致意外错误,例如&#34;突然观察者停止工作&#34;

修正 DEMO