I am facing a challenge in connecting a controller to a state (using angular ui.router) where one way of writing it works, while the other does not.
Successful example (with the controller registered under the module):
this.$stateProvider
.state('items', {
url: '/{cluster}/items',
templateUrl: App.mapPath('Items/Items.html'),
controller: 'ItemsController as controller'
});
However, this approach fails (when using an 'anonymous' controller):
this.$stateProvider
.state('items', {
url: '/{cluster}/items',
templateUrl: App.mapPath('Items/Items.html'),
controller: ItemsController,
controllerAs: 'controller'
});
It is important to note that my controller has dependencies:
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');
}
}
The template for my Items.html looks like:
<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>
Also, there is an action
directive involved:
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;
}
The main issue lies in the controller.newItem()
call. It functions correctly in the working example but fails to display anything in the console otherwise. Furthermore, the items
array (initialized in the controller's constructor) always gets populated regardless of the method used, indicating that the problem solely rests on calling controller.newItem()
...