我有以下控制器和指令声明。
<div ng-controller="DocumentController as dc" data-drop-zone url="api/document/upload">
如何连接文档控制器以在指令上调用方法。
<button ng-click="dc.start()" />
drop-zone是打字稿,定义如下。
export class DocumentDropZone implements ng.IDirective {
url: string;
constructor(public $log, public $compile) {
}
public start(): void {
this.$log.log(`start processing files...`);
}
public link: Function = (scope: any, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => {
this.$log.log(`initialising drop zone`);
... // left out for brevity.
文档控制器很简单。
class DocumentController
{
static $inject = ['$log'];
constructor(public $log: ng.ILogService) {
}
public start(): void {
// CALL THE DIRECTIVE "start" METHOD SOMEHOW...
this.$log.log(`start uploading files`);
}
}
如果我尝试在指令上使用隔离范围,则会收到错误消息:
多个指令[ngController,dropZone(module:panda)]询问
适用于以下新/隔离范围:
最佳答案
具有隔离范围的指令必须位于具有ng-controller
指令的元素的子元素上。
<div ng-controller="DocumentController as dc" >
<div my-directive command="dc.myDirCommand">
</div>
</div>
ng-controller
指令使用继承的范围。具有隔离范围的指令需要位于不同的元素上。从文档中:
通常,可以对一个元素应用多个指令,但是可能会受到限制,具体取决于指令所需的作用域类型。以下几点将有助于解释这些限制。为简单起见,仅考虑了两个指令,但它也适用于多个指令:
无范围+无范围=>两个不需要自身范围的指令将使用其父级的范围
子范围+无范围=>两个指令将共享一个子范围
子范围+子范围=>两个指令将共享一个子范围
隔离范围+无范围=>隔离指令将使用其自己创建的隔离范围。另一个指令将使用其父级的范围
孤立的作用域+子作用域=>不起作用!一个范围只能与一个元素相关。因此,这些指令不能应用于同一元素。
隔离范围+隔离范围=>不起作用!一个范围只能与一个元素相关。因此,这些指令不能应用于同一元素。
-AngularJS Comprehensive Directive API Reference -- Scope
可以使用单向绑定和
$onChanges
挂钩将命令发送到隔离指令。 app.directive("myDirective", function () {
return {
scope: { command: '<' },
bindToController: true,
controllerAs: "$ctrl",
controller: function() {
this.$onChanges = function(changes) {
if ( changes.command.currentValue === 'start'
) {
console.log(changes);
this.start();
}
};
this.start = function() {
console.log("Directive start invoked");
this.started = true;
};
},
template: '<p ng-if="$ctrl.started">Directive Started</p>'
};
});
控制器:
app.controller('DocumentController', function() {
var dc = this;
dc.startDirective = function() {
console.log("Start button clicked");
dc.myDirCommand = 'start';
};
})
DEMO on PLNKR。
关于javascript - 范围问题调用angularjs指令函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38569801/