我从 this question fork 并编辑了一个 plunker
我想做的是在数据加载后更新/填充 SELECT 元素(组合框),但有些事情不对劲。我检索数据,它位于 SELECT 元素的范围内,但模板未刷新以显示数据。有人可以have a look告诉我为什么模板不刷新?
非常感谢。
指令:
app.directive('walkmap', function() {
return {
restrict: 'A',
transclude: true,
scope: { walks: '=walkmap' },
template: '<select data-ng-options="w.postalCode for w in walks"></select>',
link: function(scope, element, attrs)
{
scope.$watch('walks', function (walks) {
scope.walks = walks;
console.log('watch triggered');
console.log(scope.walks);
});
}
};
});
索引.html:
<body ng-controller="MainCtrl">
<h1>The Walks Data:</h1>
<div walkmap="store.walks"></div>
</body>
最佳答案
解决方案:
- 您不需要另一个 $watch,
scope: { walks: '=walkmap' }
已经在观看。 - 使用
ngOptions
时,您也必须使用ngModel
。 - angularjs ng-options not working
- Working with select using AngularJS's ng-options
这是一个plunker :
app.directive('walkmap', function() {
return {
restrict: 'A',
transclude: true,
scope: { walks: '=walkmap' },
template: '<select ng-model="selected" data-ng-options="w.postalCode for w in walks"></select>'
};
});
关于AngularJS 指令 - 如何在异步数据加载后刷新模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21235302/