如何使用自定义TypeScript
指令访问控制器的范围属性?
例如,在以下代码段中,我想记录scope.message
:
/// <reference path="typings/angularjs/angular.d.ts" />
//module
module app {
var mainModule = angular.module('mainModule', []);
}
//controller
module app.testCtrl {
interface ITest {
message: string;
}
class TestCtrl implements ITest {
message: string = 'initial value'; // this is the value i want to access from my dierctive
}
angular.module('mainModule').controller('testCtrl', TestCtrl);
}
//directive
module app.directives {
export class MyDirective implements ng.IDirective {
restrict = 'A';
static instance(): ng.IDirective {
return new MyDirective;
}
link(scope: ng.IScope) {
//HOW DO I GET TO THE SCOPE PROPERTIES?
//console.log(scope.???);
}
}
angular.module('mainModule').directive('myDirective', MyDirective.instance);
}
P.S - 我使用&#34;控制器作为&#34;视图上的语法是否有所不同
答案 0 :(得分:0)
好像你在滥用角度指令的概念。如果您执行以下操作,则可以访问控制器的范围变量:
link(scope: ng.IScope) {
console.log(scope["myControllerAsAlias"].message);
}
然而,有角度的方式&#39;将变量传递给指令,如下所示:
interface IMyDirectiveScope extends ng.IScope {
message: string
}
export class MyDirective implements ng.IDirective {
restrict = 'A';
scope = {
message: "@"
};
static instance(): ng.IDirective {
return new MyDirective;
}
link(scope: IMyDirectiveScope) {
console.log(scope.message);
}
}
在你的HTML中:
<div my-directive message="myCtrlAsAlias.message"></div>