简体   繁体   中英

Call directive controller methods from outside

I write a directive that provide a tab functionality, I use latest version of AngularJS (v1). In my directive I have a controller that expose an api to a children directives, the scope is isolated in all directives:

Parent Directive

scope: {},
controller: function($scope) {
   $scope.values = [];

   this.addValue = function(value) {
        $scope.values.push(value);
   }
}

Child Directive on link function

scope: {},
transclude: true,
template: '<div ng-transclude></div>',
replace: true,
link: function(scope, element, attr, parentCtrl)
{
    parentCtrl.addValues('test')
}

In child directive I have a custom html with own controller: TestCtrl

function TestCtrl($scope){
    var vm = this;
    ... other logic
}

Implementation

<parent>
   <child>
      <div ng-controller="TestCtrl as t">
          <button ng-click="addValues('new_test')"></button>
      </div>
   </child>
</parent>

I need to call "addValues" method (inside directive controller) on click on my button.

How to organise the code to make this?

 var module = angular.module('app', []); module.controller('root', function ($scope) { $scope.test = function () { console.log('i am clicked'); } }); module.component('child', { template: '<button type="button" data-ng-click="$ctrl.click()">Click me</button>', controller: myController, bindings: { onClick: '&' } }); function myController() { var ctrl = this; ctrl.click = function () { this.onClick(); } } 
 <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script> </head> <body data-ng-app="app"> <div data-ng-controller="root"> <child data-on-click="test()"></child> </div> </body> </html> 

It is just an example Here you can read more. Hope this helps.

MAy be it will be usefull to read about angular's best practice here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM