2 ng-controller,需要在它之间共享数据

时间:2015-03-24 14:58:06

标签: javascript angularjs

嗨我的app.js中有2个控制器

app = angular.module('dbaccess',[]);
app.controller('process', function($http, $scope,$location, $service){
    $scope.update = function(user){
            $scope.master = {};
            $scope.master = angular.copy(user);
            $http.post("http://localhost:8080/dbaccess/saveData", $scope.master).success(function(data, status, headers, config){
                $scope.resp = data;
                alert("This is the data" +data.message);
                $('.form-horizontal').hide();
                $('#response-message').html().text("Hello");                    
            })
            .error(function(data){
                alert("Error " +data.message);              
            })
        }
    });
    app.controller('usrEmailAddress', function($http,$scope,$location, $service){
        $scope.email = {};          
        $http.get("http://localhost:8080/dbaccess/userlist").success(function(data){
            $scope.emails = data;
        }); 
    })

进程控制器用于将数据提交给java控制器进行处理,其他usrEmailAddress控制器用于从java控制器中获取json数据。

我有index.jsp,它有ng-model。我希望电子邮件传递给流程控制器,但是无法做到这一点。任何帮助都会很棒。

 <%@ page language="java" contentType="text/html;
       charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
         <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html> 
    <html lang="en" ng-app="dbaccess">
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <title>This is the title of the page</title>
             <link rel="stylesheet" href="/dbaccess/resources/css/bootstrap.min.css">               

            <!-- 
            <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
            <script src="http://angular-ui.github.com/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
            <script src="/dbaccess/resources/js/example.js"></script>
            -->

            <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
        </head>
         <body>
            <div class="container" ng-controller="emailAddress as address" >
                <div class="row">
                    <div class="col-lg-12"></div>
                </div>
                <form class="form-horizontal" data-toggle="validator" role="form">
                     <div class="form-group">
                        <label for="requestedBy" class="col-sm-2 control-label"> Requested By</label>
                         <div class="col-sm-3">
                            <input type="text" class="form-control" id="requestedBy" placeholder="Requestor Name" ng-model="user.requestedBy"  required/>
                         </div>
                    </div>
                     <div class="form-group">
                         <div >
                            <label for="email" class="col-sm-2 control-label">          Email Address</label>
                             <div class="col-sm-3 " ng-controller = 'usrEmailAddress'>
                                <select class="form-control" ng-model="user.email">
                                    <option value=""> --Select Email Address -- </option>
                                    <option ng-repeat="mails in emails" value={{mails.email}} >{{mails.email}}</option>
                                </select>
                            </div>  
                        </div>
                    </div>
                    <div class="form-group" >
                        <label for="approval" class="col-sm-2 control-label"> Approved By</label>
                         <div class="col-sm-3">
                            <input type="text" class="form-control" id="approval" placeholder="XYZ" ng-model="user.approvedBy" readonly/>
                        </div>  
                    </div>
                    <div class="form-group" >
                        <label for="jiraTicket" class="col-sm-2 control-label"> Jira Ticket</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="jiraTicker" ng-model="user.jira"/>
                        </div>  
                    </div>
                    <div class="form-group">
                        <label for="reason" class="col-sm-2 control-label"> Business Justification</label>
                        <div class="col-sm-3">
                            <textarea row="3" class="form-control"  required ng-model="user.requestJustification"></textarea>
                        </div>  
                    </div>
                    <div class="form-group">
                        <label for="emergency"  class="col-sm-2 control-label"> Emergency </label>
                        <div class="col-sm-3">
                            <select class="form-control" ng-model="user.emergency">
                                <option value="yes" >YES</option>
                                <option value="no"> NO </option>
                            </select>
                          </div>    
                    </div>
                    <div class="row">
                        <div class="col-md-offset-3" >
                            <button type="submit" class="btn btn-primary" ng-click="update(user,user.approvedBy='XYZ')" >Submit</button>
                        </div>
                    </div>
                </form>
                    <pre>form = {{user | json}}</pre>
                     <pre>master = {{master | json}}</pre>
            </div>  
        </body>

            <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>

            <script src="/dbaccess/resources/js/angular.js"></script>
             <script src="/dbaccess/resources/js/bootstrap.min.js"></script>
              <script src="/dbaccess/resources/js/bootstrap.js"></script>
            <script src="/dbaccess/resources/js/example.js"></script>
            <script src="/dbaccess/resources/js/validator.min.js"></script>
        </body>
    </html>

3 个答案:

答案 0 :(得分:0)

这是 AngularJS Services 的用武之地。

  

Angular服务是使用依赖注入(DI)连接在一起的可替换对象。您可以使用服务在整个应用中组织和共享代码。

详细了解AngularJS documentation中的服务。

AngularJS Services是单个实例,仅在应用程序组件依赖它时实例化。

答案 1 :(得分:0)

您可以使用有角度的servicefactory

例如:

app.factory('emailService', function($q, $http) {
  var emails;

  var getEmails = function() {
    var deferred = $q.defer();
    if (emails) { 
      deferred.resolve(emails);
    } else {
      $http.get("http://localhost:8080/dbaccess/userlist")
        .then(function(data){
          emails = data;
          deferred.resolve(emails);
        }); 
    }

    return deferred.promise;
  };

  return {
    getEmails: getEmails
  }
});

在这里,我已经使用了$q,因此无论您是否进行$http通话,您都会返回一个承诺。您可以返回已经存储在内存中的电子邮件列表,也可以获取电子邮件,将其存储在内存中,然后使用它。

您的控制器只会注入emailService并致电getEmails

app.controller('usrEmailAddress', function($scope, emailService){
  emailService.getEmails().then(function(emails) {
    $scope.emails = emails;
  });
});

app.controller('process', function($http, $scope,$location, $service, emailService){
  // [...]

  emailService.getEmails().then(function(emails) {
    $scope.emails = emails;
  });
});

无论哪个服务首先点击getEmails都会填充数据。

答案 2 :(得分:-1)

您可以在angular documentation

中查看$ emit和$ broadcast