我已经建立了一个分页指令,它带有两个参数。当前页面和总页数。<pagination page="page" number-of-pages="numberOfPages"></pagination>
问题是,在AJAX调用之后(通过ng-resource),我只会知道numberOfPages的值。但是在完成AJAX调用之前,我的指令已经被渲染。
app.controller('MyController', function ($scope, $routeParams) {
$scope.page = +$routeParams.page || 1,
$scope.numberOfPages = 23; // This will work just fine
MyResource.query({
"page": $scope.page,
"per_page": 100
}, function (response) {
//This won't work since the directive is already rendered
$scope.numberOfPages = response.meta.number_of_pages;
});
});
我宁愿等待 Controller 模板的呈现,直到AJAX调用完成。
计划B将是在完成AJAX调用后将模板与指令模板附加在一起。
我被困在两种情况下。
最佳答案
您必须使用$watch
函数来等待该值,例如:
<div before-today="old" watch-me="numberOfPages" >{{exampleDate}}</div>
指令
angular.module('myApp').directive('myPagingDirective', [
function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
scope.$watch(attr.watchMe,function(newValue,oldValue){
//check new value to be what you expect.
if (newValue){
// your code goes here
}
});
}
};
}
]);
关于angularjs - AJAX调用后的加载指令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28388452/