1

的JavaScript:

var App = angular.module('App', []);

App.controller('RootCntr', function ($scope) {
    $scope.openedShelf = false;

    console.log('controller', $scope.openedShelf);

    setTimeout(function() {
        $scope.openedShelf = true;
        console.log('controller', $scope.openedShelf);
    }, 2000);
});

App.directive('shelf', function () {
    return {
        restrict: 'E',
        scope: {
            'open': '='
        },
        link: function (scope, element, attrs) {
            console.log('linked');

            scope.$watch('open', function (newVal, oldVal) {
                console.log(newVal);
                if (newVal) {
                    console.log(true, newVal);
                }
            }, true);
        }
    };
});

的HTML:

<body ng-app="App">
    <div ng-controller="RootCntr">
        <shelf open='openedShelf'></shelf>
    </div>
</body>

当我更改指令中的值时openedShelfRootCntr它的 watch 语句没有捕捉到更新。有任何想法吗?

4

1 回答 1

2

因为 setTimeout 不执行 $apply,$digest 永远不会发生,并且观察者永远不会被调用。将 $timeout 注入您的控制器并使用 $timeout 而不是 setTimeout,就像您使用 setTimeout 一样。$timeout 由 angular 提供,它总是强制 $digest 发生。

$timeout(function() {
    $scope.openedShelf = true;
    console.log('controller', $scope.openedShelf);
}, 2000);
于 2013-08-07T18:05:59.977 回答