2015-10-17 213 views
0

我寫了一個指令,需要在網格中顯示搜索框和一些值。輸入搜索文本可能會更改網格中的值。角度指令範圍沒有反映控制器範圍的變化

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回調並與分離範圍的指令值。我觀察搜索文本並回調控制器函數,該函數更新值列表。

但是我發現指令作用域並未反映控制器作用域上'values'值的變化。

我應該怎麼做,以便只要回調更新控制器作用域上的值,子作用域就會更新?

正如您在運行示例時所看到的那樣,當搜索文本發生更改時,將調用onsearchtextchange回調並更改控制器的scope.some.values。然而,指令範圍值仍舊是舊值。

回答

0

添加一個$ scope。$ apply()在我的控制器回調中有效。

+0

也使用$ timeout而不是setTimeout。 – softvar

0

而不是使用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); 
     }); 
     } 
    }; 
}); 
+0

嗨,我最初寫了這個反彈代碼,我現在推薦使用角度反彈選項。在這裏看到我的答案:http://stackoverflow.com/a/18494567/1599609 –