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

performed a small experiment with $watch in a directive

尝试比较不同 $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!

谁能解释一下不同设置类型之间的区别?什么是 preferred/faster/different cases/etc?

在 apply/digest 周期内根据范围评估字符串以检查更改。在 apply/digest 周期内简单地调用函数来检查变化。因此,传递一个字符串s等同于传递一个像

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

传递 $scope.someVar 将导致上述结果之一,具体取决于 $scope.someVar 的计算结果是字符串还是函数。它不会为 someVar 变量设置监视,除非 $scope.someVar 是字符串 "someVar" 或 returns $scope.someVar.

的函数