簡體   English   中英

Angular指令范圍未反映控制器范圍的更改

[英]Angular directive scope not reflecting changes in controller scope

我正在寫一條指令,該指令需要在網格中顯示搜索框和一些值。 輸入搜索文字可能會更改網格中的值。

http://jsfiddle.net/rtv2222/st55azbg/5/

<div ng-controller="MyCtrl">
  <my-directive values='some.values' onsearchtextchange='onsearchtextchange' searchtext='some.searchtext'></my-directive>
  </div>

  var demo = angular.module('demo', []);
  demo.directive('myDirective', function($parse) {
  return {
    restrict: "E",
    scope: {         
        values: '=',
        searchtext: '=',
        onsearchtextchange: '&'
    },
    template: '{{values.length}} <input ng-model="searchtext">',
    link:
    function(scope, element, attrs){
        scope.$watch('searchtext', function (tmpStr){
            setTimeout(function() {
                // if searchStr is still the same..
                // go ahead and retrieve the data
                if (tmpStr === scope.searchtext)
                {
                    scope.onsearchtextchange()(scope.searchtext);
                    console.log(scope.values.length);
                }
            }, 1000);
        });
    }
}
});

function MyCtrl ($scope) {
$scope.some = {};
$scope.some.values = [{a:1}, {a:2}];
$scope.some.searchtext = "";
$scope.onsearchtextchange = function(searchtext) {
    if (searchtext && searchtext.length != 0) {
        $scope.some.values = [{a:1}];
        console.log('values.length is:' + $scope.some.values.length);
    }
    else {
        $scope.some.values = [{a:1}, {a:2}];
        console.log('values.length is:' + $scope.some.values.length);
    }
}
};

我將searchtext,onsearchtextchange回調和具有隔離范圍的值綁定到指令。 我$ watch searchtext並回調到控制器函數中,以更新值列表。

但是,我發現指令范圍不能反映控制器范圍內“值”的值的變化。

我應該怎么做,以便每當回調更新控制器作用域上的值時,就更新子作用域?

您可以在運行示例時看到,更改searchtext時,將調用onsearchtextchange回調並更改控制器scope.some.values。 指令范圍值仍然是舊值。

在我的控制器回調中添加$ scope。$ apply()可以解決問題。

除了使用setTimeout()您還可以使用AngularJS $ timeout服務,該服務在內部與$scope.$apply()一起使用。 這樣,您無需在控制器中調用$scope.$apply()

demo.directive('myDirective', function($parse, $timeout) {
  return {
    restrict: "E",
    scope: {         
        values: '=',
        searchtext: '=',
        onsearchtextchange: '&'
    },
    template: '{{values.length}} <input ng-model="searchtext">',
    link:
    function(scope, element, attrs){
        scope.$watch('searchtext', function (tmpStr){
            $timeout(function() {
                // if searchStr is still the same..
                // go ahead and retrieve the data
                if (tmpStr === scope.searchtext)
                {
                    scope.onsearchtextchange()(scope.searchtext);
                    console.log(scope.values.length);
                }
            }, 1000);
        });
      }
   };
});

暫無
暫無

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

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