2015-12-22 155 views
0

我想了解如何从内置编译指令调用外部函数。 下面是一个例子:http://plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview函数编译隔离指令 - AngularJS

HTML:

<!DOCTYPE html> 
<html ng-app="app"> 

    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
     <script src="script.js"></script> 
    </head> 

    <body ng-controller="myController as vm"> 

     <my-directive callback="vm.saveAction()" label="click me!"></my-directive> 

    </body> 

</html> 

JS:

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

app.controller('myController', function() { 
    var vm = this; 

    vm.saveAction = function() { 
     alert("foo!"); 
    } 
}); 

app.directive('myDirective', function() { 
    var directive = { 
     restrict: 'E', 
     scope: { 
      callback: '&' 
     }, 
     compile: compile, 
     link: link 
    }; 

    return directive; 

    function compile(element, attrs) { 
     var template = '<button ng-click="action()">'+attrs.label+'</button>'; 

     element.replaceWith(template); 
    } 

    function link(scope, element) { 
     scope.action = function() { 
      // ...something usefull to do... 
      scope.callback(); 
     } 
    } 
}); 

我知道我可以伊斯利做到这一点从链接功能(并从那里工作),但我真的需要从编译方法(这只是一个简化的版本来更好地指出问题)。 有人可以帮我吗?

谢谢!

回答

0

使用模板指令要做到这一点

app.directive('myDirective', function() { 
var directive = { 
    restrict: 'E', 
    scope: { 
     callback: '&', 
     label: '@' 
    }, 
    template: '<button ng-click="action()">{{label}}</button>', 
    link: link 
}; 

return directive; 

function link(scope, element, attrs) { 
    console.log(scope.label); 
    scope.action = function() { 
     // ...something usefull to do... 
     scope.callback(); 
    } 
} 

});

或者,如果你想使用编译方法,使用前或后的方法和自己编译:

function compile(element, attrs) { 
    return { 
     pre: function(scope, elem, attrs) { 
      var template = $compile('<button ng-click="action()">'+attrs.label+'</button>')(scope); 

     element.replaceWith(template); 
     }, 
     post: function (scope, elem, attrs) { 
     // or here 
     } 
    } 
}