![](/img/trans.png)
[英]AngularJS : Isolated Scope in directive with Compile in directive
[英]Functions in compile isolated directive - AngularJS
我試圖了解如何從內置編譯指令中調用外部函數。 這是一個示例: http : //plnkr.co/edit/bPDaxn3xleR8SmnEIrEf?p=preview
的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();
}
}
});
我知道我可以輕松地從鏈接函數中做到這一點(並且可以從那里開始工作),但是我確實需要從編譯方法中做到這一點(這只是簡化版本,可以更好地指出問題)。 有人可以幫我嗎?
謝謝!
使用模板指令執行此操作
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();
}
}
});
或者,如果要使用編譯方法,請使用pre或post方法並自己編譯:
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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.