Mahmut Kilic Mahmut Kilic - 19 days ago 5
AngularJS Question

Angular Directive to component angular 1.5

I have this directive, that i would like to make a component

angular.module('app')
.directive('year', function () {
var controller = ['$scope', function ($scope) {
$scope.setYear = function (val) {
$scope.selectedyear = val;
}
}];
return {
restrict: 'E',
controller: controller,
templateUrl: "views/year.html"
};
});


This is what I got so far:

angular.module('app')
.component('year', {
restrict: 'E',
controller: controller,
templateUrl: "views/year.html"
});


I am not sure how to move my
var controller
into
.component

Answer

There are few things you should do convert your directive to component

  • There is no restrict property for component as it is restricted to elements only.
  • For controller you could just set as you did at directive declaration but outside of it.
  • Controllers for components use controllerAs syntax as default so get rid of $scope

So your component should look like this...

angular.module('app') 
    .component('year', {
        controller: ComponentController,
        templateUrl: "views/year.html"
    });

function ComponentController(){
    var $ctrl = this;

    $ctrl.setYear = function (val) {
       $ctrl.selectedyear = val;
    }
}