我有一个发出xhr请求以检索一些数据的控制器。
$scope.mbProductImages = [];
$http.get('product.json').success(function(data) {
$scope.productDetails = data;
$scope.mbProductImages = $scope['productDetails']['product_images'];
console.log($scope.mbProductImages);
for(key in $scope.mbProductImages){
if ($scope.mbProductImages[key].current == true) {
$scope.currentImage = $scope.mbProductImages[key]['img_lg'];
}
}
});
我真正需要的是一个指令从$scope.productDetails
(通过属性值)从控制器中加载的数据中检索数据,我需要在指令的控制器或链接函数中而不是$ parent控制器中使用此代码...
$scope.mbProductImages = $scope[$attrs.content][$attrs.object];
console.log($scope.mbProductImages);
for(key in $scope.mbProductImages){
if ($scope.mbProductImages[key].current == true) {
$scope.currentImage = $scope.mbProductImages[key]['img_lg'];
}
}
其中,$scope[$attrs.content][$attrs.object];
在该指令相当于$scope.productDetails
从控制器...
所以我的控制器应该只有这个:
$http.get('product.json').success(function(data) {
$scope.productDetails = data;
}
而我指令的控制器将具有其他代码。
我的朋克:http ://plnkr.co/edit/xErYnlj04P5LQsMedVWi?p=preview
发生的是,获取数据的父控制器xhr请求花费的时间比加载指令所需的时间长,所以我留下了 $scope.mbProductImages
未定义的信息
我怎样才能使指令等待来自控制器的数据加载或检查何时从指令加载数据,然后应用该值?
在@Chandermani的大力帮助下,我能够看到我的错误并提出了一个好的解决方案。
控制器:
app.controller('MainCtrl', function($scope, $http) {
$http.get('mydata.json').success(function(data) {
$scope.productDetails = data;
console.log($scope.productDetails);
});
});
指示:
app.directive("myImages", function() {
return {
restrict: "E",
scope: true,
templateUrl: "template.html",
compile: function(element, attrs) {
return function(scope, element, attrs) {
scope.myContent = attrs.content;
scope.myObject = attrs.object;
scope.$watch(scope.myContent,function(newValue,oldValue){
if(newValue) {
scope.mbProductImages = newValue[scope.myObject];
console.log(scope.mbProductImages);
for(key in scope.mbProductImages){
if (scope.mbProductImages[key].current == true) {
scope.currentImage = scope.mbProductImages[key]['img_lg'];
}
}
}
})
}; // return
} // compile
}
});
您不必等待指令,而是使用监视范围变量的变化scope.$watch
。
您的监视表达式应指向您要监视的属性。就像是
$scope.$watch($attrs.content + $attrs.object, function(newValue,oldValue) {
if(newValue) {
//your logic here
}
});
watch的第一个参数应该是您要观看的对象的属性的路径。
更新:我已尝试修复您的plunkr,看看是否有帮助http://plnkr.co/edit/fKJ2nZcytKubC9JjiaTS?p=preview我基本上已经对productDetails
财产进行了监视。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句