Angularjs AJAX调用后加载指令
我已经建立了一个分页指令,它包含两个参数;当前页面和总页数Angularjs AJAX调用后加载指令,angularjs,angularjs-directive,angularjs-resource,Angularjs,Angularjs Directive,Angularjs Resource,我已经建立了一个分页指令,它包含两个参数;当前页面和总页数 问题是,我只知道AJAX调用后numberOfPages的值(通过ng资源)。但是我的指令在AJAX调用完成之前就已经呈现了 app.controller('MyController', function ($scope, $routeParams) { $scope.page = +$routeParams.page || 1, $scope.numberOfPages = 23; // This will work
问题是,我只知道AJAX调用后numberOfPages的值(通过ng资源)。但是我的指令在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;
});
});
我宁愿等待控制器模板的呈现,直到AJAX调用完成
计划B是在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;
});
});
我无法解决这两种情况。您必须使用
$watch
函数等待值,如:
<div before-today="old" watch-me="numberOfPages" >{{exampleDate}}</div>
重要事项:您的指令可能使用一个独立的作用域,但即使如此,同样的原则仍然有效
如果使用
resolve
from,则可以在呈现视图之前将meta
或meta.number\u页面注入控制器
//routes.js
angular.module('app')
.state('some_route', {
url: '/some_route',
controller: 'MyController',
resolve: {
meta: ['MyResource', function (MyResource) {
return MyResource.query({
"page": $scope.page,
"per_page": 100
}, function (response) {
return response.meta;
});
}]
}
});
//controllers.js
app.controller('MyController', function ($scope, $routeParams, meta) {
$scope.page = +$routeParams.page || 1,
$scope.numberOfPages = meta.number_of_pages;
});
但是,在一切完成之前,难道不可能阻止渲染吗
- 我认为ng if会这样做,与ng show/ng hide相反,ng show/ng hide只会改变实际显示
谢谢。我不知道链接(而不是控制器)。我认为可以使用ng hide隐藏指令,并在值更改时显示它。但是,难道不可能在一切完成之前阻止渲染吗;我让手表的功能正常了。但是,一旦检测到新的更改,我如何重新呈现该指令?您能否举例说明如何处理隔离作用域?这同样有效:)。但是我更喜欢将延迟呈现逻辑保留在指令的JS代码(而不是HTML)中。ng if是一个更好的解决方案,因为它应该是指令(即HTML)的所有者来决定是否加载它,所以在HTML元素上使用ng if比添加scope.$watch函数更容易。我有同样的问题,从ajax加载一个大数据集,在呈现指令之前需要它。谢谢你的提示!这个答案正是我想要的。伟大的