我正在尝试创建一个从其他地方加载数据的指令。
这是我的指令:
(function() {
var module = angular.module('HomeModule', ['StorageService']);
module.directive("home", ['storage',
function(storage) {
return {
restrict: 'A',
templateUrl: "modules/home/directives/home-directive.html",
controllerAs: "mediaCtrl",
controller: function() {
var ctrl = this;
ctrl.medias = [];
storage.get_all(function(items) {
var tmp = [];
for (id in items) {
tmp.push(items[id]);
}
ctrl.medias = tmp;
});
// setTimeout(function() {
// ctrl.medias = [{name: "test"}];
// }, 3000);
}
};
}
]);
})();
还有我的模板:
<input type="search" ng-model="search.name" placeholder="filter medias..." />
<ul>
<li ng-repeat="media in mediaCtrl.medias | filter:search" >
{{media.name}}
</li>
</ul>
我不明白的是,只要我在过滤器中输入内容,它就会更新,然后显示数据。我什至尝试使用 setTimeout
来查看问题是否出在我的自定义服务上,但不是。
最佳答案
您可以将数据更新函数包装在 $scope.$apply() 调用中,如下所示:
storage.get_all(function(items) {
$scope.$apply(function () {
var tmp = [];
for (id in items) {
tmp.push(items[id]);
}
ctrl.medias = tmp;
});
});
关于javascript - Angular.js 指令与加载数据的两种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25214384/