gpt4 book ai didi

AngularJs:为什么异步数据到达时我的指令内的范围不更新?

转载 作者:行者123 更新时间:2023-12-03 08:58:03 24 4
gpt4 key购买 nike

我有一个带有隔离范围的指令,它通过引用获取一个范围变量

angular.module('myApp')
.directive('myDirective', function() {
return {
scope: {
items: '='
},
templateUrl: 'template.html',
replace: true,
controller: 'myDirectiveCtrl',
controllerAs: 'ctrl'
};
})
.controller('myDirectiveCtrl', function($scope) {
this.items = $scope.items;
});

这是这样传递的:
    <div my-directive items='items'></div>

在外部 Controller 中,数据被异步加载,并且传递给指令的范围项被更新:
angular.module('myApp', [])
.controller('myCtrl', function($scope) {

$scope.setItems = function() {
$scope.items = [
'Here',
'There',
'Everywhere'
];
};
});

加载数据时,我的指令之外的范围会更新,但内部不会

我的html:
      <div my-directive items='items'></div> <!-- this doesn't update --> 

Outside directive
<ul ng-repeat='i in items'> <!-- this does update -->
<li>{{i}}</lu>
</ul>

<button ng-click="setItems()">Set items</button>

如何在我的指令中获取我的范围以进行更新?难道我

Plunker here

最佳答案

当 Angular 第一次运行你的指令的 Controller 函数时,你的 $scope.items === undefined , 所以当你做 this.items = $scope.items , 你的 this.items === undefined也。

就是这样。之后没有任何变化this.items .

这与 $scope.items 不同。 . $scope.items是双向绑定(bind)到外部范围的,因此每当 Angular 检测到外部更改时,它都会设置隔离范围变量。

最简单的方法(在我看来也是最合适的)是使用 $scope直接在指令中的属性:

<div>
Inside directive
<ul ng-repeat="i in items">
<li>{{ i }}</li>
</ul>
</div>

如果您想将 Controller 用作 ViewModel 而不是范围(我不知道您为什么要这样做),您可以这样做:
$scope.$watchCollection("items", function(newVal, oldVal) {
ctrl.items = newVal;
});

编辑:

在 Angular 1.3 中,您还可以执行 bindToController: true在指令的定义中, Controller 属性“ items”将获得 $scope.items 的双向绑定(bind)得到。然后,你甚至不需要做 this.items = $scope.items; :

您的 forked plunker为了显示。

关于AngularJs:为什么异步数据到达时我的指令内的范围不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com