您可以通过执行以下操作来实现此目的:
首先,设置主应用程序 HTML,
<body ng-app="app">
<div ng-controller="MainCtrl as vm">
Emergency text: {{vm.emergencyText}}
<my-directive on-alarm="vm.emergency(vm.parentVar, directiveVar)"></my-directive>
</div>
</body>
您会注意到on-alarm
回调包含对vm.parentVar
仅引用 的变量的引用MainCtrl.parentVar
,该变量directiveVar
将来自指令本身。
现在我们可以创建我们的主控制器:
angular.module('app', []);
angular
.module('app')
.controller('MainCtrl', function () {
// Initialise the emergency text being used in the view.
this.emergencyText = '';
// Define our parent var, which is a parameter called to the emergency function.
this.parentVar = 'This is an emergency';
// Define the emergency function, which will take in the parent
// and directive text, as specified from the view call
// vm.emergency(vm.parentVar, directiveVar).
this.emergency = function (parentText, directiveText) {
this.emergencyText = parentText + ' ' + directiveText;
}.bind(this);
});
最后,我们将创建指令。
angular
.module('app')
.directive('myDirective', function () {
return {
scope: {
onAlarm: '&'
},
link: function (scope, element, attrs) {
scope.onAlarm({ directiveVar: 'from myDirective' });
}
}
});
魔术发生在我们调用之后scope.onAlarm({ directiveVar: 'from myDirective' });
。这个调用告诉 Angular 警报回调函数(紧急)将可以访问directiveVar
,我们在前面的视图中通过 引用on-alarm="vm.emergency(vm.parentVar, directiveVar)"
。在幕后,Angular 将通过其 $parse 服务正确地将 parentVar 范围解析为 MainCtrl 并将directiveVar 范围解析为指令。
这是一个完整的plunkr。