如何在Angular JS中将视图中的值传递给控制器​​?

时间:2015-10-31 12:37:20

标签: javascript angularjs

我已经开发了一个控制器,它根据从后端通过$ 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 个答案:

答案 0 :(得分:1)

在你的情况下,

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