Angular Directive to component angular 1.5

做~自己de王妃 提交于 2019-12-24 01:09:06

问题


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


回答1:


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;
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/40664609/angular-directive-to-component-angular-1-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!