我有两个指令。首先是使用(包括)第二个。
这是我的子指令:
angular.module('myApp')
.directive('radioType', function() {
return {
restrict: 'E',
scope: {
question: '=',
onAnswer: '&'
},
template: [
'<div>{{vm.question.text}}<br/>',
'<div>',
'<button ng-repeat="a in vm.question.answers track by $index" ng-click="onSelected(a)">{{a.text}}</button>',
'</div>',
'<button ng-click="myFunction()">Radio</button>',
'</div>'
].join(''),
controller: ['$scope', function($scope) {
$scope.myFunction = function() {
console.log("hello from radio controller");
$scope.vm.onAnswer();
};
$scope.onSelected = function(question) {
$scope.vm.question.answer = question.text;
console.log(question);
};
}],
controllerAs: 'vm',
bindToController: true
};
});
这是我的主要指令:
angular.module('myApp')
.directive('question', function($compile) {
var combo = '<div>COMBO - {{vm.content.text}}</div>';
var radio = [
'<radio-type question="vm.content" onAnswer="vm.onAnswer()"></radio-type>'
].join('');
var input = [
'<input-type question="vm.content"></input-type>',
].join('');
var getTemplate = function(contentType) {
var template = '';
switch (contentType) {
case 'combo':
template = combo;
break;
case 'radio':
template = radio;
break;
case 'input':
template = input;
break;
}
return template;
}
var linker = function(scope, element, attrs) {
scope.$watch('vm.content', function() {
element.html(getTemplate(scope.vm.content.type))
$compile(element.contents())(scope);
});
}
return {
restrict: "E",
link: linker,
scope: {
content: '='
},
controller: ['$scope', function($scope) {
$scope.onAnswer = function() {
console.log("answer");
};
}],
controllerAs: 'vm',
bindToController: true
};
})
在子指令中,我有按钮,当有人单击其中一个按钮时,我想从主指令中调用函数。
我已在子指令中包含 onAnswer: '&'
,并且我在主目录模板内分配函数,但我可以使其正常工作。
这是 Plunker 显示我的问题:http://plnkr.co/edit/iWU4L3IJLHtADHBl2dIh?p=preview
欢迎任何其他建议。
最佳答案
scripts.js
上有 2 个错误。
在第 6 行,您的属性不应采用驼峰命名法:
'<radio-type question="vm.content" on-answer="vm.onAnswer()"></radio-type>'
在第 46 行,您的函数应该位于对象 vm
内:
$scope.vm.onAnswer = function() {
关于javascript - 内部指令与主指令的通信 - 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589453/