簡體   English   中英

當值在AngularJS之外更改時,AngularJS指令范圍不會更新

[英]AngularJS directive scope not updating when value changed outside of AngularJS

我正在開始使用AngularJS,但有一個菜鳥問題,我不確定該如何解決。 我正在修改一個超出angular的值(我僅出於演示目的將其放在.run部分中),然后嘗試運行$ apply,以便Angular將注意到需要更新范圍。

但是,在以下代碼中,{{currentState}}值被設置為“初始值”,並且從未更新為“第二值”。

什么是獲取價值更新的正確方法?

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>

如果您的用例涉及一個計時器,那么Angular提供了自己的計時器服務,稱為$interval ,它將調用包裝在一個scope.$apply為您服務。 您應該使用它而不是setTimeout

現在,在這種情況下,由於您需要在服務和作用域中的值之間進行單向綁定,因此可以在指令中設置$watch

 .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.$watch(function () { return userNotificationService.getStatus(); }, function (newVal) {
                scope.currentState = userNotificationService.getStatus();
             });
        }
    };

理想情況下,您將通過在控制器中創建這種單向(或雙向)綁定(將其留空)來實現此目的。 您在控制器上定義的$scope將可用於該指令(如果將$scope: false$scope: true設置$scope: false ),則可以將link函數保留為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM