0

So, here's a sample code:

<div ng-controller="MyControllerOne">
    <span ng-click="foobar()">Click Me!</span>
</div>

Can I, from that template, without changing controller, call the function foobar() in MyControllerTwo:

.controller('MyControllerOne', function($scope) {
    //some code
})
.controller('MyControllerTwo', function($scope) {
    // method I wanna call
    function foobar(){
    }
})
1
  • You could make use of services here. Add a method in the service that manipulates any persistent data, which should also be in your service Commented Nov 8, 2016 at 9:47

3 Answers 3

1

While not the prettiest solution, it is technically possible...ish.

If you update your HTML to:

<div ng-controller="MyControllerOne">
    <span ng-controller="MyControllerTwo as mct" ng-click="mct.foobar()">Click Me!</span>
</div>

Then you should get your expected results.

Sign up to request clarification or add additional context in comments.

Comments

1

You can call method which is in another controller from the template by injecting '$controller' service in the controller. Below is the demo and code.

You can see demo here: http://plnkr.co/edit/oBEKxamgJv0uDVsJJwth?p=preview

HTML:

  <body ng-controller="MainCtrl">
    <div ng-click="fooBar()">Click Me!</div>
  </body>

JS:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $controller) {
  $controller('SubCtrl', {$scope: $scope});
});

app.controller('SubCtrl', function($scope) {
  $scope.fooBar = function() {
    alert('second controller');
  };
});

Comments

1

Pretty old question, but if any one is still looking for an alternative answer ... It should be possible to use $emit or $broadcast.

Like from ControllerOne :

$rootScope.$broadcast('callToFoobat',{});

And then from ControllerTwo :

$scope.$on('callToFoobat', function(){ 
    // whatever you want, so why not a call to foobar 
})

Just a rough solution. Might be more elegant or lighter than just $rootScope.$broadcast. And maybe think about stoping propagation whenever needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.