[英]How to pass the javascript object from view to controller using angular JS?
[英]How to pass a value from view to a controller in Angular JS?
我已經開發了一個控制器,該控制器可以通過數據構建表,並通過$ http.get從后端獲取它們。
我想知道如何從視圖中將值傳遞給此控制器,該視圖告訴必須使用哪個URL來獲取他將用於構建表的數據。
我怎樣才能做到這一點?
我試圖這樣做,但是沒有用。
HTML:
<div ng-controller = "paginatorController" ng-init = "initilize(1)">
.....
.....
</div>
JS:
demo.factory("ServiceURL", [function() {
return {
url: [
"/privado/usuario/getcoduser",
"/privado/usuario/list"
]
};
}]);
demo.controller( "demoCtrl", ["$http", "$scope", "ServiceURL", function($http, $scope, ServiceURL) {
this.initialize = function( type) {
self.type = type;
//Inside of this function self.type is correctly initialized
}
//But here, self.type is undefined, and gives me an error!!!
$http.get(ServiceURL.url[self.type])
.success(function(response){
//More code
}
}).error(function(response){
//More code
});
}]);
如果我想做的事情不可能,還有其他方法可以做我想做的事情嗎?
我找到了解決方案:
我創建了一個外部函數,在其中放置了所有用於構建表的控制器代碼,然后在控制器中突出顯示了對該函數的調用,傳遞了正確的參數,並且該函數可以正常工作。
HTML:
<div ng-controller = "demoCtrl1">
.....
.....
</div>
<div ng-controller = "demoCtrl2">
.....
.....
</div>
<div ng-controller = "demoCtrl3">
.....
.....
</div>
JS:
function buildTable($http, $scope, ServiceURL, indexURL){
$http.get(ServiceURL.url[indexURL])
.success(function(response){
//More code
}
}).error(function(response){
//More code
});
}
demo.controller( "demoCtrl1", ["$http", "$scope", "ServiceURL", function($http, $scope, ServiceURL) {
buildTable($http, $scope, ServiceURL.url[1]);
}]);
demo.controller( "demoCtrl2", ["$http", "$scope", "ServiceURL", function($http, $scope, ServiceURL) {
buildTable($http, $scope, ServiceURL.url[2]);
}]);
demo.controller( "demoCtrl3", ["$http", "$scope", "ServiceURL", function($http, $scope, ServiceURL) {
buildTable($http, $scope, ServiceURL.url[3]);
}]);
使用此解決方案,我有可能擁有一個以上的表,而這些表僅使用相同的代碼而不是復制-粘貼我的代碼。
就你而言
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.