GRo*_*ing 2 javascript ajax angularjs angularjs-directive angularjs-scope
我有一个控制器,它发出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'];
}
}
});
Run Code Online (Sandbox Code Playgroud)
我真正需要的是一个指令从$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'];
}
}
Run Code Online (Sandbox Code Playgroud)
其中,$scope[$attrs.content][$attrs.object];在该指令相当于$scope.productDetails从控制器...
所以我的控制器应该只有这个:
$http.get('product.json').success(function(data) {
$scope.productDetails = data;
}
Run Code Online (Sandbox Code Playgroud)
而我的指令的控制器将拥有其他代码.
我的傻瓜:http://plnkr.co/edit/xErYnlj04P5LQsMedVWi?p =preview
发生的事情是,父控制器xhr请求获取数据所需的时间比指令加载要长,所以我得到了$scope.mbProductImages unfined
如何使指令等待来自控制器的数据加载或检查从指令加载的时间然后应用该值?
在@Chandermani的帮助下,我能够看到我的错误并找到了一个很好的解决方案.
控制器:
app.controller('MainCtrl', function($scope, $http) {
$http.get('mydata.json').success(function(data) {
$scope.productDetails = data;
console.log($scope.productDetails);
});
Run Code Online (Sandbox Code Playgroud)
});
指示:
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
}
});
Run Code Online (Sandbox Code Playgroud)
您不要使指令等待,而是使用指向范围变量的更改scope.$watch.
您的监视表达式应指向您要观看的属性.就像是
$scope.$watch($attrs.content + $attrs.object, function(newValue,oldValue) {
if(newValue) {
//your logic here
}
});
Run Code Online (Sandbox Code Playgroud)
watch的第一个参数应该是您要监视的对象的属性的路径.
更新:我试图修复你的plunkr看看有帮助http://plnkr.co/edit/fKJ2nZcytKubC9JjiaTS?p=preview
我基本上把手表放在productDetails财产上.