在一个指令中用$ watch进行了一个小实验

时间:2015-01-07 11:19:50

标签: javascript angularjs angularjs-directive angularjs-scope

尝试比较不同$ watch参数传递之间的差异:

代码:

angular.module('app', [])
    .controller( 'someCtrl', [ '$scope', function ( $scope ) {
        $scope.someVar = 'a';
    }])

    .directive( 'dirName', [ function() {
        var directive = {};
        directive.restrict = 'AE';

        var link = function ( scope, element, attrs ) {
            console.log('link!');

            scope.$watch( 'someVar', function() {
                console.log('var-string!');
            });

            scope.$watch( scope.someVar, function () {
                    console.log ('var with scope!');
                } );

            scope.$watch( function () {
                    return scope.someVar;
                }, function () {
                    console.log('function returns the var!');
                } );
        }

        directive.compile = function ( scope, element, attr ) {
            console.log('compile!');
            return link;
        }   

        return directive;
    }]);

Html:

<body ng-app="app">
    <div ng-controller="someCtrl">
        <div dir-name>{{someVar}}</div>
        <button ng-click="someVar='b'">b!</button>
    </div>

我们有Onload / parse:

compile!
link! (this parts is quite clear for understanding)
var-string!
var with scope!
function returns the var

点击:

var-string!
function returns the var!

有人可以解释不同设置类型之间的区别吗?什么是首选/更快/不同的案例/等?

1 个答案:

答案 0 :(得分:1)

在应用/摘要周期中,根据范围评估字符串以检查更改。在应用/摘要周期中简单地调用函数以检查更改。因此,传递字符串s相当于传递类似

的函数
function () {
   return $scope.$eval(s);
}

传递$scope.someVar将导致上述其中一项,具体取决于$scope.someVar是否对字符串或函数求值。它不会设置someVar变量的监视,除非$scope.someVar是字符串"someVar"或函数返回$scope.someVar