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

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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()"
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.