Angularjs sharing methods between controllers

前端 未结 2 430
余生分开走
余生分开走 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题