Search code examples
angularjsionic-frameworkangular-controllerangular-template

Ionic - AngularJS: calling methods via template outside of Controller


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(){
    }
})

Solution

  • 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.