繁体   English   中英

如何将值从视图传递到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]);

}]);

使用此解决方案,我有可能拥有一个以上的表,而这些表仅使用相同的代码而不是复制-粘贴我的代码。

就你而言

  1. 您正在函数“ initialize()”中定义“ self.type”。 由于这是该函数的本地变量,因此无法在$ http.get方法中访问此变量“ self”。
  2. 在此过程中,您正在函数内部定义此变量,除非调用该函数,否则不会对其进行初始化。 因此,请尝试在没有功能帮助的情况下初始化变量(可能在控制器或服务内部)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM