我寫了一個指令,需要在網格中顯示搜索框和一些值。輸入搜索文本可能會更改網格中的值。角度指令範圍沒有反映控制器範圍的變化
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。然而,指令範圍值仍舊是舊值。
也使用$ timeout而不是setTimeout。 – softvar