[英]Angular TypeScript state controller
我正在嘗試將一個控制器附加到一個狀態(使用角度ui.router),但我不明白為什么以一種方式編寫它卻不能以另一種方式編寫。
工作示例(在模塊上注冊了控制器):
this.$stateProvider
.state('items', {
url: '/{cluster}/items',
templateUrl: App.mapPath('Items/Items.html'),
controller: 'ItemsController as controller'
});
但這不是(使用“匿名”控制器):
this.$stateProvider
.state('items', {
url: '/{cluster}/items',
templateUrl: App.mapPath('Items/Items.html'),
controller: ItemsController,
controllerAs: 'controller'
});
請記住,我的控制器具有依賴性:
export class ItemsController {
static $inject = ['$scope', 'itemsResource', '$stateParams'];
constructor(
scope: IItemsScope,
itemsFactory: IItemsResource,
stateParams: IClustersStateParams) {
scope.items = itemsFactory.query({ cluster: stateParams.cluster });
}
public newItem(): void {
console.log('test');
}
}
我的Items.html模板是:
<div class="items">
<ul class="add">
<li>
<action icon-style="glyphicon-plus" text="Add new item" activated="controller.newItem()"></action>
</li>
</ul>
<ul>
<li ng-repeat="item in items">
<item item="item"></item>
</li>
</ul>
</div>
和action
指令:
export class ActionDirective implements ng.IDirective {
restrict = 'E';
replace = true;
template = '<a class="action"><span class="glyphicon {{iconStyle}}" aria-hidden="true"></span><span>{{text}}</span></a>';
scope = {
iconStyle: '@iconStyle',
text: '@text',
activated: '&'
};
public link(scope: IActionDirectiveScope, instanceElement: ng.IAugmentedJQuery, instanceAttributes: ng.IAttributes, controller: any): void
{
instanceElement.on('click', (): void => {
scope.activated();
});
}
public static factory(): ng.IDirectiveFactory {
const directive = () => new ActionDirective();
return directive;
}
}
問題是controller.newItem()
調用。 在工作示例中,它將正常運行,否則它將不會在控制台上顯示任何內容。 另外我注意到items
數組(在控制器的構造函數中設置)將始終被填充(與方法無關),因此僅調用controller.newItem()
不會起作用...
您應該將控制器作為STRING名稱傳遞:
this.$stateProvider
.state('items', {
url: '/{cluster}/items',
templateUrl: App.mapPath('Items/Items.html'),
//controller: ItemsController,
controller: "ItemsController",
controllerAs: 'controller'
})
如文檔http://angular-ui.github.io/ui-router/site/#/api/ui.router.state。$ stateProvider中所述
controller
:控制器fn
, 如果以字符串形式傳遞 ,則應與新關聯的范圍或已注冊控制器的名稱關聯。 可選地,可以在此處聲明ControllerA。
但是我們也可以只構造函數(類名)。
我將控制器放入名稱空間:
namespace MyModule{
export class ItemsController {
static $inject = ['$scope', 'itemsResource', '$stateParams'];
constructor(
scope: IItemsScope,
itemsFactory: IItemsResource,
stateParams: IClustersStateParams) {
scope.items = itemsFactory.query({ cluster: stateParams.cluster });
}
public newItem(): void {
console.log('test');
}
}
}
在這里檢查
並具有以下狀態def:
.state('items', {
url: '/{cluster}/items',
//templateUrl: App.mapPath('Items/Items.html'),
templateUrl: 'Items/Items.html',
controller: MyModule.ItemsController,
controllerAs: 'controller'
})
這個視圖Items / Items.html
<div class="items">
...
<button icon-style="glyphicon-plus" text="Add new item" >xxx
..
</div>
我們可以看到它正在工作。 在這里檢查
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.