Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/445.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当值在AngularJS之外更改时,AngularJS指令范围不更新_Javascript_Angularjs - Fatal编程技术网

Javascript 当值在AngularJS之外更改时,AngularJS指令范围不更新

Javascript 当值在AngularJS之外更改时,AngularJS指令范围不更新,javascript,angularjs,Javascript,Angularjs,我刚开始学习AngularJS,有一个我不知道如何解决的noob问题。我正在修改angular之外的一个值(我把它放在.run部分只是为了演示),然后尝试运行$apply,这样angular就会注意到范围需要更新 但是,在下面的代码中,{currentState}}值被设置为“Initial value”,并且永远不会更新为“Second value” 获取要更新的值的正确方法是什么 angular.module("exampleApp", []) .run(function(userNotif

我刚开始学习AngularJS,有一个我不知道如何解决的noob问题。我正在修改angular之外的一个值(我把它放在.run部分只是为了演示),然后尝试运行$apply,这样angular就会注意到范围需要更新

但是,在下面的代码中,{currentState}}值被设置为“Initial value”,并且永远不会更新为“Second value”

获取要更新的值的正确方法是什么

angular.module("exampleApp", [])
.run(function(userNotificationService) {
    userNotificationService.setStatus("Initial value");
    setTimeout(function() {
       userNotificationService.setStatus("Second value");
    }, 1000);
})
.factory('userNotificationService', function($rootScope) {
   var currentState = 'Unknown state'; // this should never be displayed
   return {
     setStatus: function(state) {
        $rootScope.$apply(function() {
            currentState = state;
        });
     },
     getStatus: function() {
        return currentState;
     }
  };
}).directive('currentState', function(userNotificationService) {
    return {
        restrict: 'AE',
        scope: false, // set to false so that directive scope is used for transcluded expressions
        link: function(scope) {
            scope.currentState = userNotificationService.getStatus();
        }
    };
}).controller("defaultCtrl", function ($scope) {
// does nothing
});
html如下所示:

<body ng-controller="defaultCtrl">
    <div current-state>
        current state: {{ currentState }}
    </div>
</body>

当前状态:{{currentState}}

如果您的用例涉及计时器,Angular将提供自己的计时器服务,名为
$interval
,它将调用封装在
范围内。$apply
为您提供。您应该使用它,而不是
setTimeout

在本例中,由于您需要在服务和范围中的值之间进行单向绑定,因此可以在指令中设置
$watch

指令('currentState',函数(userNotificationService){ 返回{ 限制:“AE”, scope:false,//设置为false,以便指令作用域用于转包表达式 链接:功能(范围){ 作用域.$watch(函数(){return userNotificationService.getStatus();},函数(newVal){ scope.currentState=userNotificationService.getStatus(); }); } };

理想情况下,您可以通过在控制器中创建此单向(或双向)绑定(保留为空)。您在控制器上定义的
$scope
将可用于指令(如果您设置
$scope:false
$scope:true
),然后您可以将
链接保持为空。

scope.currentState=newVal也可以工作,而不是调用userNotificationService.getStatus()同样。@AlexanderMarquardt这取决于第一次执行,
newVal
可能是
undefined
,如果
$watch
的第一个参数是一个字符串。如果操作很昂贵,那么最好使用
newVal
并防止
未定义。