简体   繁体   English

如何从AngularJS中的不同控制器传递所选值

[英]How to pass the selected value from different controllers in AngularJS

I have started to learn AngularJS yesterday. 我昨天开始学习AngularJS。 I am trying to use it to create a web application which uses a simple web service. 我正在尝试使用它来创建使用简单Web服务的Web应用程序。

Right now I have three select boxes. 现在我有三个选择框。

First select : orgType ->gets all orgType from the service at load (I got this working) 首先选择:orgType->在加载时从服务中获取所有orgType(我已经开始工作了)

Second select: state-> populates a bunch of states from local json object(fine till here) 第二选择:state->从本地json对象填充一堆状态(直到此处为止)

Third select: cities-> gets all the cities for the SELECTED state from the web service(this is where I am stuck I can't get the the third select to populate as state changes). 第三选择:citys->从Web服务获取SELECTED状态的所有城市(这是我无法解决的问题,因为状态变化,我无法获取第三选择来填充)。

This is my code for now 这是我现在的代码

HTML: HTML:

<body>
    <div  id='test'>

        <select class="form-control" ng-controller="typeController" >
            <option ng-repeat="types in row" >{{types.type}}</option>

        </select>

        <select class="form-control"   ng-controller="statesController" >
            <option ng-repeat="state in states" >{{state.abbreviation}}</option>

        </select>

        <select class="form-control" ng-controller="citiesController" >
            <option ng-repeat="city in cities" >{{city.city}}</option>

        </select>

    </div>  
</body>
</html> 

Controllers.js Controllers.js

    var myApp=angular.module('myApp',[]);

    myApp.controller('typeController',['$scope','$http',function ($scope,$http){
      $http.get('someURL path=%2FOrgTypes').success(function(data){
        var jsonData = $.xml2json(data);
        console.log(jsonData.row);
        $scope.row=jsonData.row;

      });
    }]);

    myApp.controller('statesController',['$scope','$http',function ($scope,$http){
      $http.get('data/states.json').success(function(data){

         console.log('states',data);
         $scope.states=data;

      });
    }]);

    myApp.controller('citiesController',['$scope','$http',function changeCity($scope,$http){
      $http.get('someURL ?path=/Cities?state=MD').success(function(data){
//hardcoding city to MD for now
           var jsonData = $.xml2json(data);
           console.log('cities', jsonData);
           $scope.cities=jsonData.row;
        });

    }]);

Thanks for your help! 谢谢你的帮助!

create a service that stores your state abbreviation 创建一个存储状态缩写的服务

.factory('myFactory', function() {
    var state = '';
    return {
        setState: function(val) {
            state = val;
        },
        getState: function() {
            return state;
        }
    }
}

then you can watch the getState function in this service in your controller. 那么您就可以在控制器中观看此服务中的getState函数。

$scope.$watch(function () {
  return myFactory.getState();
}, function (val) {
   // execute your get method with the new value or whatever you want to do
});

and of course make sure you inject all your dependencies appropriately. 当然,请确保您适当地注入了所有依赖项。

further more why do all of these selects need their own controller? 此外,为什么所有这些选择都需要自己的控制器? move all the http calls to services and have them all share the same scope. 将所有http调用移至服务,并使它们都共享相同的作用域。

Is there any specific reason you want so many controllers? 您想要这么多控制器有什么特殊原因吗? For the simple page you have, one is enough. 对于您拥有的简单页面,一个就足够了。 And ng-change is the right way to go. ng-change是正确的方法。 First thing you need to do is to add ng-model to the state and city selects so that we have something for 2-way binding. 您需要做的第一件事是将ng-model添加到州和城市选择中,以便我们进行双向绑定。 And then use ng-change on the state select to receive the selected state and do corresponding action there for the city. 然后在select的状态上使用ng-change来接收选择的状态,并对该城市进行相应的操作。

Example

 <div ng-app="myApp" >
  <div ng-controller="myCtrl">
   <select class="form-control" ng-model="selectedState" ng-change="changedState(selectedState)">
     <option ng-repeat="state in states" >{{state.abbreviation}}</option>
   </select>
   <select class="form-control" ng-model="citiesController" >
     <option ng-repeat="city in cities" >{{city.city}}</option>
   </select>    
  </div>       
</div>

js: js:

myApp.controller('myCtrl', function($http, $scope){    
    $scope.changedState=function(selectedState){
      $http.get('url?state='+selectedState).success(data){
          $scope.cities = data;
      };
    }       
}

Or you can create a watch function for the selectedState to achieve the same thing. 或者,您可以为selectedState创建一个监视函数以实现相同的目的。 Hope this help~ 希望有帮助〜

If you are trying to access the data from a url which is different than the domain your page is, you might be hitting the Same Origin Policy problem. 如果您尝试从与页面所在域不同的URL访问数据,则可能会遇到“ 同源策略”问题。 Basically this is not a problem, but a security feature where a web browser permits scripts contained in web page A to access data in a web page B, but only if both web pages have the same origin. 基本上这不是问题,而是一种安全功能,其中网络浏览器允许网页A中包含的脚本访问网页B中的数据,但前提是两个网页的来源相同。 An origin is defined as a combination of URI scheme, hostname, and port number . 来源定义为URI方案,主机名和端口号的组合

One typical solution to deal with this problem is to pass a callback function name in the url of the web service. 解决此问题的一种典型解决方案是在Web服务的URL中传递回调函数名称。

somewebapiendpoint?callback=some_function_name

Provided the webapi endpoint will return the result wrapped inside some_function_name script. 假设webapi端点将返回包装在some_function_name脚本中的结果。 Since the server can execute script inside your page, you should be careful (basically trust the server :)) about this approach. 由于服务器可以在页面内执行脚本,因此应谨慎(基本上信任服务器:))。

Another solution is to enable CORS 另一个解决方案是启用CORS

In order to share data between controllers, you should create a service. 为了在控制器之间共享数据,您应该创建一个服务。 However, in this case I would have a single controller on <div id="test"> that would have access to each of the select elements' ngModels. 但是,在这种情况下,我在<div id="test">上只有一个控制器,该控制器可以访问每个select元素的ngModels。

<body>
    <div id="test" ng-controller="MyFormController">
        <select class="form-control" ng-model="type">
            <option ng-repeat="types in row" >{{types.type}}</option>
        </select>

        <select class="form-control" ng-model="state">
            <option ng-repeat="state in states" >{{state.abbreviation}}</option>
        </select>

        <select class="form-control" ng-model="city">
            <option ng-repeat="city in cities" >{{city.city}}</option>
        </select>
    </div>  
</body>

Also, consider using the controllerAs syntax . 另外,请考虑使用controllerAs语法 It's better to keep your data out of the $scope , as it helps separate concerns and is more in line with Angular2 architecture. 最好将您的数据放在$scope ,因为它有助于分离问题,并且更符合Angular2架构。

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

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