如果在$ timeout之后修改$ scope,则无法正确呈现我的视图。我不明白为什么。如果我不先执行$ timeout,它会起作用。
http://plnkr.co/edit/oGuPgt7VaYKgPFh00lDV?p=preview
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js'></script>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script>
angular.module('treeApp', [])
.controller('TreeController', ['$scope', '$timeout', function($scope, $timeout) {
// This works
// $scope.nodes = {
// 1:{node_id:1, text:'foo text', parent_id:null, child_ids:[2,3]},
// 2:{node_id:2, text:'bar text', parent_id:1, child_ids:[]},
// 3:{node_id:3, text:'abc text', parent_id:1, child_ids:[]}
// }
// $scope.top_ids = [1]
// This doesn't work
$timeout(function() {
$scope.nodes = {
1:{node_id:1, text:'foo text', parent_id:null, child_ids:[2,3]},
2:{node_id:2, text:'bar text', parent_id:1, child_ids:[]},
3:{node_id:3, text:'red text', parent_id:1, child_ids:[]}
}
$scope.top_ids = [1]
}, 1000)
}])
</script>
<div ng-app="treeApp">
<script type="text/ng-template" id="node.html">
<li node_id="{{node_id}}" ng-repeat="node_id in node_ids" ui-tree-node
ng-init="node = nodes[node_id]">
{{node.text}}
<ol ng-include="'node.html'" ng-init="node_ids = node.child_ids"></ol>
</li>
</script>
<div ng-controller="TreeController">
<ol ng-include="'node.html'" ng-init="node_ids = top_ids"></ol>
<pre>{{top_ids | json}}</pre>
<pre>{{nodes | json}}</pre>
</div>
</div>
最佳答案
<ol ng-include="'node.html'" ng-init="node_ids = top_ids"></ol>
用
node_ids
初始化top_ids
。这是一次性的任务,而不是绑定。当使用$timeout
时,top_ids
的值在分配点为undefined
。最简单的解决方案是将
$scope.top_ids
重命名为$scope.node_ids
并摆脱ng-init
。关于javascript - Angular View 未更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26839559/