AngularJs - Calling controller function from directive

≡放荡痞女 提交于 2019-12-04 16:54:50
Manikandan Velayutham

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

app.controller("Ctrl", function ($scope) {
  $scope.test = function () {
   console.log("Hi you called ctrl function");
  };
  $scope.param = function(name){
  console.log("My name is " + name);
  }
  $scope.testing = function(role){
  console.log("I'm a "+ role);
  }
});

app.directive("testDir", function () {
  return {
    scope: {
      test: "&callFuc",
      param:"&withparam",
      testing:"&"
    },
    template: `<button ng-click="test()">Call Test!
               </button>
               <button ng-click="param({name:'Mani'})">With param!
               </button>
               <button ng-click="clickHere()">Click Me!
               </button>`,
    link:function(scope){
        scope.clickHere = function(){
            scope.testing({msg:"Javascript Developer"});
        };
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="exApp">
  <div ng-controller="Ctrl">
    <div test-dir call-fuc="test()" withparam="param(name)" testing="testing(msg)"></div>
  </div>
</div>

This example is without parameter;

   scope: {
                file: '=',
                fileName: '=',
                test: '&',
            }
<a ng-click="test()">Call test</a> // in directive

<md-content file-dropzone layout="column" test="vm.test()"
            layout-align="center center" class="md-list-item-text"
            md-whiteframe="1" style="padding:1em;margin:0.5em 0.5em;" 
            flex>
   File drop zone
</md-content>

You can access the directive controller by specifying the fourth variable in link function.

Updated Link function:-

link: function (scope, element, attrs, ctrl) {
  console.log(ctrl.test());
}

You need to pass ctrl as fourth parameter inside link function.

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