簡體   English   中英

如何將屬性添加到自定義角度指令

[英]How to add attribute to custom angular directive

我需要向自定義的角度指令添加屬性,但是我不知道如何將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>

因此,基本上我想向該角度指令添加width屬性。

謝謝您的幫助!

您只需要像使用所有其他三個變量一樣將其傳遞給范圍:

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM