繁体   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