角度指令至零件角度1.5 [英] Angular Directive to component angular 1.5

查看:69
本文介绍了角度指令至零件角度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"
    });

我不确定如何将var controller移到.component

推荐答案

应该将指令转换为组件的几件事

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

  • 该组件没有没有限制属性,因为它仅限于元素.
  • 对于控制器,您可以像在指令声明中一样进行设置,但要在其外部中进行设置.
  • 组件的控制器默认使用 controllerAs 语法,因此摆脱了 $ scope
  • 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;
    }
}

这篇关于角度指令至零件角度1.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆