Angularjs:我可以让我的指令在控制器API回调后运行吗?
Angularjs: Can I have my directive run after controller API callback
首次发问者。如果我的术语不太对,我很抱歉,我刚接触angularjs
我有一个controller
,它通过HTTP调用获得产品列表
contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams', '$http', '$location',
function ($scope, $routeParams, $http, $location)
{
$http.get('products').success(function (products)
{
$scope.productList = products
})
}
和一个我想访问该产品列表的directive
。
contractManagementControllers.directive("priceBands",function($http)
{
return {
scope: true,
restrict: 'AE',
replace: 'true',
templateUrl: 'Partials/PriceBand.html',
link: function ($scope, ele, attrs, c)
{
// use $scope.productList
}
});
我的问题是事情发生的顺序。控制器函数首先运行,然后是指令链接函数,然后是设置产品列表的回调函数。因此,$scope.productList
在指令链接函数中未定义,并给出错误
是否有办法强制链接函数等待,直到回调完成?
设置默认值为productList
,以免出现未定义变量错误
contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams', '$http', '$location',
function ($scope, $routeParams, $http, $location)
{
$scope.productList = [];
$http.get('products').success(function (products)
{
$scope.productList = products
})
}
,然后观察productList
in指令的变化:
contractManagementControllers.directive("priceBands",function($http)
{
return {
scope: true,
restrict: 'AE',
replace: 'true',
templateUrl: 'Partials/PriceBand.html',
link: function ($scope, ele, attrs, c)
{
$scope.watch('productList', function(newValue, oldValue) {
//Perform here if you need
});
}
});
无需在angularjs
中等待callback
。只要把$scope.productList=[];
放在你的controller as first line
里。它不会给指令undefined
在你的指令link function
中只写$watch
函数来观察元素的变化。
相关文章:
- MeteorJS:在带有回调的vzaar api上正确使用wrapAsync
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何通过bxSlider回调api处理事件
- Google Data API上的OOP Javascript回调方法
- JavaScript回调函数和Google Feed API
- Google API 的客户端库不会执行回调
- Google Maps JavaScript API v3:getDetails(请求,回调),用于多个位置
- 如何向 chrome 扩展 API 添加回调函数
- 用于Javascript的Skydrive API中的回调URL
- Chrome API未在嵌套回调中注入cookie
- 如何在Node.js上使用twitter api实现回调函数
- 回调返回响应,但当在API中发送时,响应在节点JS中显示为空白
- 谷歌地图API v3:缩放更改后是否有回调或事件侦听器
- 使用 Javascript/JQuery 使用 Ajax 加载 Google Maps API,回调设置不正确
- Google JS API: gapi.auth.signIn 回调函数问题
- 如果失败,角度回调 API 将添加错误消息
- 无需回调即可使用通知 API 的正确方法
- 创建回调 API
- 如何使用QUnit回调api
- 如何将现有回调 API 转换为承诺