Javascript 通过嵌套指令访问隔离父作用域
在本例中,我试图动态设置给定数组可以显示的Javascript 通过嵌套指令访问隔离父作用域,javascript,angularjs,Javascript,Angularjs,在本例中,我试图动态设置给定数组可以显示的限制 app view.html <things data="things.data" settings="things.settings"></things> <ul> <li ng-repeat="thing in data | limitTo: limit"> {{thing.name}} <span ng-show="$index==settings.
限制
app view.html
<things data="things.data" settings="things.settings"></things>
<ul>
<li ng-repeat="thing in data | limitTo: limit">
{{thing.name}}
<span ng-show="$index==settings.limit-1">
<show-more min="settings.limit" max="data.length"></show-more>
</span>
</li>
</ul>
<li>
<a href="#" ng-click="toggle()">{{text}}</a>
</li>
在这里,您会注意到尚未设置限制
things.html
<things data="things.data" settings="things.settings"></things>
<ul>
<li ng-repeat="thing in data | limitTo: limit">
{{thing.name}}
<span ng-show="$index==settings.limit-1">
<show-more min="settings.limit" max="data.length"></show-more>
</span>
</li>
</ul>
<li>
<a href="#" ng-click="toggle()">{{text}}</a>
</li>
问题开始了:
- 当用户调用
toggle()
以“显示更多”时,我试图将limit
的值更新为data.length
的最大值,该值绑定到max
- 当用户调用
toggle()
以“显示较少”时,我试图将limit
的值更新为settings.length
的最小值,该值绑定到min
显示更多指令.js
$scope.$on('thingsCallback', function(e,d){
$scope.things = d;
});
.directive('things', function() {
return {
scope : {
data : "=",
settings : "="
},
restrict: 'E',
replace: true,
controller: function($scope){
$scope.$watch('settings',function(){
if($scope.settings){
$scope.limit = $scope.settings.limit;
}
});
},
templateUrl: 'things.html'
};
})
.directive('showMore', function() {
return {
scope : {
min : "=",
max : "="
},
restrict: 'E',
replace: true,
controller: function($scope){
$scope.text = 'show more';
$scope.toggle = function(){
$scope.text = ($scope.max==$scope.$parent.limit)?'show more':'show less';
$scope.$parent.limit = ($scope.min==$scope.$parent.limit)?$scope.max:$scope.min;
//Shows the value has updated, but the ng-repeat does not update?
console.log($scope.$parent.limit);
}
},
templateUrl: 'showMore.html'
};
})
$scope.$parent.limit
似乎在更改,但ng repeat
不会更新以显示剩余结果
- 如何通过嵌套指令更改隔离父范围
- 有更好的方法吗
您可以尝试在toggle()的末尾重新编译元素:
将其包装在$scope.$apply($scope.$parent.limit=…)中;指令通常不会触发摘要循环。@ZackArgyle正在获取一个$apply
错误。从未在这种情况下使用过——请提供一个例子好吗?