Reputation: 355
First of all, I have looked for examples and none of them offer the solution I'm looking for.
I have an AngularJS directive and it works fine, but actually I really want it with Typescript.
My question is not related to the way to translate the javascript code to typescript, but I really want to understand data binding with Controller, because when translated into typescript the view has stopped working.
Here is my code:
Directive
namespace Directives {
"use strict";
export interface ISidebarController {
toolbarButtons: any[];
toolbarBck: string;
toolbarBtnAction: Function;
}
class SidebarController implements ISidebarController {
static $inject = ["$location"];
constructor(private $location: ng.ILocationService) {
}
public toolbarBck = "sidebar-disabled";
public toolbarButtons = [
{
enabledImgIcon: "../resources/img/sidebar/enabled/list_icon.png",
disabledImgIcon: "../resources/img/sidebar/disabled/list_icon.png",
enabledBck: "sidebar-enabled",
disabledBck: "sidebar-disabled",
isEnabled: true,
isPressed: false
}, {
enabledImgIcon: "../resources/img/sidebar/enabled/create.png",
disabledImgIcon: "../resources/img/sidebar/disabled/create.png",
enabledBck: "sidebar-enabled",
disabledBck: "sidebar-disabled",
isEnabled: true,
isPressed: false
}
];
public toolbarBtnAction = function(btnObj, index) {
btnObj.isPressed = !btnObj.isPressed;
};
}
function sidebar(): ng.IDirective {
return {
restrict: "E",
templateUrl: "widgets/sidebar.html",
replace: true,
scope: {},
controller: SidebarController,
controllerAs: "vm",
bindToController: true
};
}
angular.module("app.confVersion").directive("sidebar", sidebar);
}
View
<div class="row" ng-repeat="toolBtn in toolbarButtons" ng-click="toolbarBtnAction(toolBtn, $index)">
<div class="{{toolBtn.isPressed ? toolBtn.enabledBck : toolBtn.disabledBck}}">
<img ng-src="{{toolBtn.isPressed ? toolBtn.enabledImgIcon : toolBtn.disabledImgIcon}}">
</div>
</div>
Upvotes: 0
Views: 113
Reputation: 355
Finally, I find the solution. The problem was the use of Doctype in the view. I remove it and now it works fine!
My fault for not including the doctype in example, my apologies.
Upvotes: 0
Reputation: 3678
You're almost there; you're just running into an issue with the 'controllerAs' option. You're specifying that the controller for your directive should be referenced in the template using the prefix 'vm', but your template isn't using that. As @iberbeu mentioned, you should make sure that you're using the controller alias:
<!-- Note the use of 'vm.toolbarButtons' below! -->
<div class="row" ng-repeat="toolBtn in vm.toolbarButtons" ng-click="toolbarBtnAction(toolBtn, $index)">
<div class="{{toolBtn.isPressed ? toolBtn.enabledBck : toolBtn.disabledBck}}">
<img ng-src="{{toolBtn.isPressed ? toolBtn.enabledImgIcon : toolBtn.disabledImgIcon}}">
</div>
</div>
Upvotes: 2