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

performed a small experiment with $watch in a directive

本文关键字:一个 实验 指令 watch      更新时间:2023-09-26

尝试比较不同$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;
    }]);

目录:

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

加载/解析我们有:

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

点击时:

var-string!
function returns the var!

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

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

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

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