$scope.$watch 没有捕捉到指令修改的值

$scope.$watch not catching the value modified by directive

我的指令将焦点放在我的跨度上并分配 boolean 值,即每当我按下 shifttab 时,focusToSpan 为 true,但是,此更改没有反映在我的 控制器 模板 中。我什至用 $scope.$watch 检查了 focusToSpan 变量,如下所示

指令

(function() {
    'use strict';
    angular.module("my.page").directive('getFocusToSpan', function() {
        return {
            link: function(scope, elem, attr, ctrl) {
                elem.bind("keydown keypress", function(event) {
                    if (event.which === 16) {
                        $('.iconclass').attr("tabIndex", -1).focus();
                        scope.focusToSpan = true;
                    }
                });
            }
        };

    });

})();

控制器

     $scope.$watch('focusToSpan', function(newValue) {
     if (angular.isDefined(newValue)) {

     alert(newValue);
     }
     });

没有得到 called.May 我知道在指令中对控制器变量所做的更改将如何反映在控制器和模板中。 谢谢, 巴拉吉.

您在 angular 之外操作的上下文 scope/binding 不会更新。要更新绑定,您需要 运行 摘要循环来更新所有范围级别的绑定。

在您的情况下,您正在从自定义事件更新 angular scope 变量,因此您需要通过对范围执行 $apply() 方法来手动 运行 摘要循环

代码

elem.bind("keydown keypress", function(event) {
    if (event.which === 16) {
       $('.iconclass').attr("tabIndex", -1).focus();
       scope.focusToSpan = true;
       scope.$apply();
    }
});