【发布时间】:2017-03-29 07:37:03
【问题描述】:
我正在尝试制作一个最小但花哨的 AngularJS 教程示例,我遇到了一个问题,即在为模型更新整个树后(在 ng-change 更新的范围内),驱动的模板顶级 ng-repeat 根本不会重新渲染。
但是,如果我在战略位置添加代码$scope.data = {},它就会开始工作;但随后显示闪烁而不是漂亮和流畅。这不是 AngularJS 自动数据绑定如何工作的一个很好的例子。
我错过了什么;什么是正确的解决方法?
确切的代码 - 从下拉列表中选择一个国家 - 这个 jsFiddle 不起作用:http://jsfiddle.net/f9zxt36g/ 这个 jsFiddle 工作但闪烁:http://jsfiddle.net/y090my10/
var app = angular.module('factbook', []);
app.controller('loadfact', function($scope, $http) {
$scope.country = 'europe/uk';
$scope.safe = function safe(name) { // Makes a safe CSS class name
return name.replace(/[_\W]+/g, '_').toLowerCase();
};
$scope.trunc = function trunc(text) { // Truncates text to 500 chars
return (text.length < 500) ? text : text.substr(0, 500) + "...";
};
$scope.update = function() { // Handles country selection
// $scope.data = {}; // uncomment to force rednering; an angular bug?
$http.get('https://rawgit.com/opendatajson/factbook.json/master/' +
$scope.country + '.json').then(function(response) {
$scope.data = response.data;
});
};
$scope.countries = [
{id: 'europe/uk', name: 'UK'},
{id: 'africa/eg', name: 'Egypt'},
{id: 'east-n-southeast-asia/ch', name: 'China'}
];
$scope.update();
});
模板由 ng-repeat 驱动:
<div ng-app="factbook" ng-controller="loadfact">
<select ng-model="country" ng-change="update()"
ng-options="item.id as item.name for item in countries">
</select>
<div ng-repeat="(heading, section) in data"
ng-init="depth = 1"
ng-include="'recurse.template'"></div>
<!-- A template for nested sections with heading and body parts -->
<script type="text/ng-template" id="recurse.template">
<div ng-if="section.text"
class="level{{depth}} section fact ng-class:safe(heading);">
<div class="level{{depth}} heading factname">{{heading}}</div>
<div class="level{{depth}} body factvalue">{{trunc(section.text)}}</div>
</div>
<div ng-if="!section.text"
class="level{{depth}} section ng-class:safe(heading);">
<div class="level{{depth}} heading">{{heading}}</div>
<div ng-repeat="(heading, body) in section"
ng-init="depth = depth+1; section = body;"
ng-include="'recurse.template'"
class="level{{depth-1}} body"></div>
</div>
</script>
</div>
我错过了什么?
【问题讨论】:
-
这应该是
ng-include的问题,因为它创建了新的范围。如果您只是渲染您的json 数据<select ng-model="country" ng-change="update()" ng-options="item.id as item.name for item in countries"> </select>{{data}},您会发现它运行顺利。我建议使用原型链模型(如$scope.data.data)来保留模板内的范围。 -
感谢 anoop 和 Aperion。我仍然不确定是什么导致了问题,但我找到了一个不需要我消除递归或使用
ng-include的修复程序。看起来这是ng-init和ng-repeat之间的不良交互。如果我按如下方式更改它,jsfiddle.net/fL951g83 以消除在 ng-repeat 中的循环变量上使用 ng-init,它可以正常工作。会不会和stackoverflow.com/questions/15355122/…有关?
标签: angularjs angularjs-ng-repeat