2

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

mtkilic
  • 1,213
  • 1
  • 12
  • 28

2 Answers2

4

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;
    }
}
Poyraz Yilmaz
  • 5,847
  • 1
  • 26
  • 28
  • Thank you for detail explanation. This kinda works, but I think something else is broke now. Because I have my Year button, but my dropdown selection is not displaying anymore. – mtkilic Nov 17 '16 at 21:45
  • 1
    because components are using controllerAs syntax and default alias is $ctrl. you should update your component html with it too. As an example with $scope ng-click="clickBtn()" with controllerAs ng-click="$ctrl.clickBtn()" – Poyraz Yilmaz Nov 17 '16 at 21:52
0

Your component should look like this:

function YearController() {
  var $ctrl = this;

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

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

For more details, please read the following Stack Overflow question for more deatils: Angular 1.5 component vs. old directive - where is a link function? and the official documentation: https://docs.angularjs.org/guide/component

Also, please note that components are restricted to elements only by default.

Community
  • 1
  • 1
Tome Pejoski
  • 1,582
  • 2
  • 10
  • 34