Angularjs sharing methods between controllers

前端 未结 2 420
余生分开走
余生分开走 2020-12-09 04:51

I was reading this article on Angular validation and thought it would be good to use in my own project. It\'s working really well and I\'d like to extend it accessing method

相关标签:
2条回答
  • 2020-12-09 05:17

    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.

    In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events.

    Ideally in your usage you would write an event in controller 1 as:

    $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. That way you can communicate to the other app.

    0 讨论(0)
  • 2020-12-09 05:24

    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:

    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.

    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. See the plunk I've updated it to demonstrate what you're asking.

    0 讨论(0)
提交回复
热议问题