Ionic - AngularJS: calling methods via template outside of Controller

点点圈 提交于 2019-12-12 03:05:11

问题


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:


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.




回答2:


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');
  };
});



回答3:


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.



来源:https://stackoverflow.com/questions/40477112/ionic-angularjs-calling-methods-via-template-outside-of-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!