Search code examples
angularjsangularjs-directiveangularjs-scopeangularjs-serviceangularjs-routing

calling ng-view controller method from outside controller?


HTML:

<html ng-app="san">
<head>
</head>
<body ng-controller="sanctrl">
<div>
    AngularJS</div>
<div ng-view="">
</div>
<button type="button" ng-click="init()" class="btn btn-blue">
    Save</button>
</body>
</html>

Main Controller:

san.controller('sanctrl', function ($scope, $http, $q, $location, $anchorScroll, $filter, dataFactory) {
//nothing in this controller.
});

ng-view controller:

san.app.controller('cereals', function ($scope, dataFactory) {
  $scope.init(){
    $scope.test = "test";
  };
});

I am trying to call init method from outside ng-view scope. Is it possible? if not then what are the options we have?


Solution

  • You can use a broadcast event that you trigger:

      $rootScope.$broadcast('testEvent', testArray);
    

    Then in 2nd controller you can listen for the event:

      $scope.$on('testEvent', function(event, array) {
    
          // Do stuff here
    
       });