我是Angular.js的新手,我需要在我的应用程序之间进行指令之间的一些通信,我阅读了一些关于链接和需求的文档,但是无法准确理解它是如何工作的.
我有一个简单的例子:活小提琴:http://jsfiddle.net/yw235n98/5/
HTML:
<body ng-app="myApp">
First Directive :
<first-dir >
<h3>{{firstCtrl.data}}</h3>
<button ng-click="firstCtrl.set('NEW VALUE')">Change Value</button>
</first-dir>
Second Directive :
<second-dir>
<h3>{{secondCtrl.data}}</h3>
</second-dir>
Run Code Online (Sandbox Code Playgroud)
Javascript:
(function(){
var app = angular.module('myApp', []);
app.directive("firstDir", function(){
return {
restrict : 'E',
controller : function(){
this.data = 'init value';
this.set = function(value){
this.data = value;
// communication with second Directive ???
}
},
controllerAs : 'firstCtrl'
};
});
app.directive("secondDir", function(){
return {
restrict : 'E',
controller : function(){
this.data …
Run Code Online (Sandbox Code Playgroud) 如何存根/模拟读取为 的指令/组件ViewChild
?
例如,使用 angular.io 中的简单指令:
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
假设我正在测试并将使用AppComponent
读取为:HighlightDirective
ViewChild
@ViewChild(HighlightDirective) theHighlightDirective: HighlightDirective
Run Code Online (Sandbox Code Playgroud)
存根指令是:
@Directive({
selector: '[appHighlight]'
})
export class StubbedHighlightDirective {
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
由于组件正在尝试读取,即使您在单元测试中HighlightDirective
声明,也将是。StubbedHighlightDirective
theHighlightDirective
undefined
例子:
it('HighlightDirective is defined', () => {
// This test fails
expect(component.theHighlightDirective).toBeDefined();
});
Run Code Online (Sandbox Code Playgroud)
如果您忽略 tslint 中的某些内容或使用as
关键字,则可以解决此问题:
Version 1: Just ignore some things in tslint so compiler doesn't complain
it('HighlightDirective is defined', () …
Run Code Online (Sandbox Code Playgroud)