如何将属性添加到自定义角度指令

时间:2015-03-23 07:30:18

标签: javascript html css angularjs

我需要向自定义角度指令添加属性,但我不知道如何将属性(宽度)从html部分绑定到管理行为的javascript。

这是html:

<div class="dropdown btn-group">
    <button type="button" class="btn btn-default" data-bind="dropdown-label">{{initialValue}}</button>
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
    <span class="caret"></span>
    <span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu dropdown-menu-scrollable" role="menu" aria-labelledby="dropdownMenu">
    <li role="presentation" ng-repeat="value in values"
            ng-click="clickHandler(value,$event)">
        <a role="menuitem" tabindex="-1">{{value}}</a>
    </li>
</ul>

这是html背后的javascript:

angular.module('platform.directives').directive('dropdownComponent', function() {
    'use strict';
return {
    restrict: 'E',
    scope: {
        initialValue: '@',
        values: '=',
        selectedValue: '='
    },
    templateUrl: 'modules/directives/dropdown/dropdown.html',
    link: function(scope) {
        scope.clickHandler = function findAndFillSelectedValueAndCloseDropDownArea(value, event) {
            var $target = $(event.currentTarget);
            $target.closest('.btn-group')
                    .find('[data-bind="dropdown-label"]').text($target.text())
                    .end()
                    .children('.dropdown-toggle').dropdown('toggle');
            scope.selectedValue = value;
            return false;
        };
    }
};
});

这是用法:

<dropdownComponent 
   initial-value={{'PERMISSION.CREATE.DROPDOWN.RESOURCE'|translate}}
   selected-value="permissionCtrl.permission.resourceId"
   values="permissionCtrl.resources" 
   width="200px">
</dropdownComponent>

所以基本上我想为这个angular指令添加一个width属性。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您只需将其传递到范围,就像使用其他所有3个变量一样:

scope: {
        initialValue: '@',
        values: '=',
        selectedValue: '=',
        width: "@"
    },

现在你可以在指令的javascript中使用scope.width来添加元素,例如。

在HTML中(顺便说一下,您应将dropdownComponent更改为dropdown-component):

<dropdown-component 
        initial-value={{'PERMISSION.CREATE.DROPDOWN.RESOURCE'|translate}} 
        selected-value="permissionCtrl.permission.resourceId" 
        values="permissionCtrl.resources" 
        width="200px"></dropdown-component>

编辑:在您的指令HTML中,将第一个按钮更改为:

<button type="button" 
        class="btn btn-default" 
        data-bind="dropdown-label" 
        ng-style="width: {{width}}">{{initialValue}}</button>
相关问题