![](/img/trans.png)
[英]How to pass an item from ng-repeat to a controller created/loaded by ng-include?
[英]How to pass data to a ng-include controller?
我有一個ng-include
html元素,並希望將一些數據從外部傳遞給控制器。
主controller
從http webservice
fetches
json
data
,並將數據提取到作用域變量climadata
。
以下是pseudocode
,但你明白了:
function mainController($scope, $http) {
$http.get().then(
$scope.climadata = response.clima;
);
}
<div ng-controller="mainController">
<div ng-include="'clima.html'" ng-controller="climaController" onload="climamodel = climadata"></div>
</div>
這工作正常,但climadata永遠不會到達climaController
。 檢查如下:
function climateController($scope) {
console.log($scope.climamodel); //prints "undefinied"
};
在控制台中始終未定義climamodel,但為什么?
這是有效的,你獲得undefined
的原因是因為,你通過$http
請求得到數據,因此,在你獲得數據之前climaController
將執行,此時沒有范圍變量調用climadata
。
檢查這個DEMO
你可以看到控制台打印undefined
但是在ajax請求之后數據可用之后你將獲得部分HTML
頁面上的數據。
如果要在ajax完成后加載inclcude
,請使用ng-if
<div ng-if="climadata" ng-include="'clima.html'" ng-controller="climaController"></div>
如果climadata
存在,那么只有這個div進程才意味着include
只有在climadata
可用的情況下才有效。
你可以從onload="climamodel = climadata"
首先,您需要將
onload
更改為ng-load
或ng-init
。 因為onload
無法讀取角度屬性。
您可以使用
$rootScope
,將值從控制器傳遞到另一個控制器是有幫助的。
function climateController($rootScope ) { console.log($rootScope.climamodel); };
還有其他一些細節,你可以到這里: AngularJS:如何在控制器之間傳遞變量?
試試這個:
function mainController($scope, $http) {
$scope.data={};
$http.get().then(
$scope.data.climadata = response.clima;
);
}
<div ng-controller="mainController">
<div ng-include="clima.html" ng-controller="climaController">/div>
</div>
我認為最好的方法是使用$broadcast
它本質上是一種將事件傳播到子范圍的服務(讀取:子控制器)。 子控制器使用$on
服務偵聽$broadcast
事件。
以下是如何實現它。 在您的MainController中 :
function mainController($scope, $http, $broadcast) { //injected broadcast
$http.get().then(
$scope.climadata = response.clima;
$scope.$broadcast('climaData', $scope.climadata); //broadcast event 'climaData' and send '$scope.climadata' as argument.
);
}
在您的climateController中 :
function climateController($scope) {
$scope.$on('climaData', function(event, args) { //listener for 'climaData' event.
console.log(args); //args contains $scope.climadata sent from the main controller.
})
};
我認為通過范圍繼承共享數據會創建意大利面條代碼。 應該檢查您的代碼和模板以了解正在發生的事情。
對於您的問題,我將創建一個將加載和緩存數據的服務。 該服務可以注入兩個控制器。
這是示例代碼
module.factory('UserService', ['$http', '$q', function($http, $q){
var userAPI = {};
var userData = null;
var isLoading = false;
userAPI.getMyData = function(){
var deferred = $q.defer();
if(userData != null){
deferred.resolve(userData);
} else if(isLoading === false) {
isLoading = true;
$http.get('/api/data/data').then(function(resp){
userData = resp.data;
deferred.resolve(userData);
}, function(err){
deferred.reject(err);
});
}
return deferred.promise;
};
return userAPI;
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.