简体   繁体   中英

AngularJs calling function in link from controller

I have a parent controller and i want to call a function in link from controller but when try to access it gives

TypeError: undefined is not a function

My Controller:

scope.test = function(m)
{
 linkfunction(m);
}

My Directive: .......... link: function(scope, element, attrs) {

 linkfunction = function (n){
  ........somethings........
  }

  ..........
  }

How can i call function in link from directive?

1) Using Isolated Scope

HTML

<div test-directive callback-fun="testFunction()"></div>

Controller:

$scope.testFunction = function(){
  console.log("test")
}

Directive:

.directive('testDirective', function() {
     return {
         scope: {
            callbackFun: '&'
         },
         link: function(scope, element, attrs) 
         {
            scope.callbackFun();
         }
     }
 })

2) Without using Isolated Scope

HTML:

<div test-directive></div>

Controller:

$scope.testFunction = function(){
  console.log("test")
}

Directive:

.directive('testDirective', function() {
     return {
         link: function(scope, element, attrs) 
         {
            scope.testFunction();
         }
     }
 })

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