2017年11月16日 星期四

AngularJs Pass function to directive without execute it.

HAngularJs Pass function to directive without execute it

Background
- angularjs v1.x


view

<div ng-controller="myController">
 <a class="btn" ng-click="someMethod(myFunction())" prevent-default></a>
</div>


controller

'use strict';

(function () {
    // Create controller variable
    function myController($scope) {        

       $scope.someMethod = function (action) {
          $scope.actionName = action;            
       };

       $scope.myFunction = function () {
       var fn = function () {
            alert("Hello There!");
          };
       return fn;
       }; 
    };

    // Register the controller    
    angular.module("umbraco").controller("myController", myController);
})();

Explantion

put the you own logic inside

var fn = function () {
    alert("Hello There!");
};

replace the alert by your own logic.

at last return the fn

and when pass the function

ng-click="someMethod(myFunction())"

myFunction must be include bracket (),

declare the function and assign a variable fn for that, it will not execute while parsing when the website startup. It just expression, it will execute it when you evaluate the expression in where you want to.

$eval($scope.actionName()); 

P.S The declaration of function very very critical, and end of the function must return fn

沒有留言:

張貼留言