简体   繁体   English

Angularjs在控制器之间共享方法

[英]Angularjs sharing methods between controllers

I was reading this article on Angular validation and thought it would be good to use in my own project. 我正在阅读关于Angular验证的这篇文章 ,并认为在我自己的项目中使用它会很好。 It's working really well and I'd like to extend it accessing methods in other controllers upon successful validation of the form. 它的工作非常好,我希望在成功验证表单后扩展它访问其他控制器中的方法。 I've tried various ways of doing this but I can't seem to see the methods in the $scope object. 我尝试了各种方法,但我似乎无法看到$ scope对象中的方法。

<!DOCTYPE html>
<html>
  <head>
    <link data-require="bootstrap-css@3.0.0" 
      data-semver="3.0.0" 
      rel="stylesheet" 
      href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
    <script data-require="angular.js@1.0.8" 
      data-semver="1.0.8" 
      src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
    <script src="rcSubmit.js"></script>
    <script src="loginController.js"></script>
    <script src="loginApp.js"></script>
  </head>

  <body>
    <div class="container">
      <div class="row">
        <div class="col-xs-12 col-sm-6 col-sm-offset-3">
          <h1>Simple Login Form</h1>
          <form name="loginForm" novalidate 
            ng-app="LoginApp" ng-controller="LoginController" 
            rc-submit="login()">
            <div class="form-group"
              ng-class="{'has-error': rc.loginForm.needsAttention(loginForm.username)}">
             <input class="form-control" name="username" type="text" 
              placeholder="Username" required ng-model="session.username" />
             <span class="help-block" 
              ng-show="loginForm.username.$error.required">Required</span>
            </div>
            <div class="form-group"
              ng-class="{'has-error': rc.loginForm.needsAttention(loginForm.password)}">
              <input class="form-control" name="password" type="password" 
                placeholder="Password" required ng-model="session.password" />
              <span class="help-block" 
                ng-show="loginForm.password.$error.required">Required</span>
            </div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary pull-right" 
                value="Login" title="Login">
                <span>Login</span>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

I was hoping that someone can tell me what I'm missing in order to make this work. 我希望有人可以告诉我我缺少什么才能使这项工作。 I've forked a plunkr . 我分叉了一个傻瓜

The proper way to do this would be with an angular service. 这样做的正确方法是使用角度服务。 For example: 例如:

app.factory('svc', function () {
    var msg="original...";
    return {
        setMessage: function(x) {
            msg=x;
        },
        getMessage: function() {
            return msg;
        }
    };
});

This way you can access the fucntions inside svc in any controller that you inject svc into: 这样你可以在你注入svc任何控制器中访问svc里面的fucntions:

app.controller("ctrl1",function($scope,svc,$timeout){
  $scope.someText=svc.getMessage();
  $scope.$watch("someText",function(v){
    svc.setMessage(v);
  });
});

app.controller("ctrl2",function($scope,svc){
  $scope.msg=svc.getMessage();
  $scope.$watch(svc.getMessage,function(v){
    $scope.msg=v;
  });
});

See this demo plunk (I ignored that plunk you provided because it had a lot of noise). 看到这个演示插件 (我忽略了你提供的插件,因为它有很多噪音)。

EDIT 编辑

Executing the service method and form validation are not really related to each other, see plunk . 执行服务方法和表单验证并不真正相互关联, 请参阅plunk

EDIT 编辑

If you want to use the services or controllers of one app inside another, just reference the dependencies in your main app and call the services defined in your main app inside your second app. 如果您想在另一个应用程序中使用一个应用程序的服务或控制器,只需引用主应用程序中的依赖项,并在第二个应用程序内调用主应用程序中定义的服务。 If your main app is called demoApp1 , then you could create another app called dempApp2 and reference demoApp1 in demoApp2 and use any services defined in demoApp1 inside demoApp2 . 如果你的主要应用程序被称为demoApp1 ,那么你可以创建一个名为另一个应用程序dempApp2和参考demoApp1demoApp2并使用定义的任何服务demoApp1demoApp2 See the plunk I've updated it to demonstrate what you're asking. 看到插件我已经更新它以证明你在问什么。

The best approach for you to communicate between the two controllers is to use events. 您在两个控制器之间进行通信的最佳方法是使用事件。

Scope Documentation 范围文档

In this check out $on , $broadcast and $emit . 在此检查$on$broadcast$emit

In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events. 在一般用例中, angular.element(catapp).scope()的使用被设计为在角度控制器之外使用,就像在jquery事件中一样。

Ideally in your usage you would write an event in controller 1 as: 理想情况下,在您的使用中,您可以在控制器1中编写一个事件:

$scope.$on("myEvent", function (event, args) {
   $scope.rest_id = args.username;
   $scope.getMainCategories();
});

And in the second controller you'd just do 在第二个控制器中,你只需要做

$scope.initRestId = function(){
   $scope.$broadcast("myEvent", {username: $scope.user.username });
};

Can you try including the firstApp module as a dependency to the secondApp where you declare the angular.module . 您可以尝试将firstApp模块作为依赖项secondApp在您声明angular.module That way you can communicate to the other app. 这样你就可以与其他应用程序进行通信。

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

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