Samantha J Samantha J - 3 months ago 6
AngularJS Question

How can I pass a variable into a directive?

I have this directive:

app.directive('dropdown', ['$timeout',function ($timeout) {
return {
require: '^ngModel',
restrict: 'E',
template: '<div id="dropdownDirective" class="btn-group" dropdown>' +
'<button class="btn dropdown-toggle" ng-disabled="ngDisabled" dropdown-toggle>' +
'{{ items[ngModel].name }}' +
'<span class="caret"></span>' +
'</button>' +
'<ul class="dropdown-menu" role ="menu" aria-label="dLabel">' +
'<li ng-repeat="item in items">' +
'<a href="#" ng-bind="item.name" ng-click="select(item)" >< / a >' +
'</li>' +
'</ul>' +
'</div>',
scope: {
ngModel: '=', // selected item
items: '=', // items to select from
ngDisabled: '=',
ngChange: '&'
},
link: function (scope: any, element, attrs, ngModelCtlr) {
// selection changed handler
scope.select = function (item, ngModel) {
scope.ngModel = item.id;
$timeout(scope.ngChange, 0);
ngModelCtlr.$setDirty();
};
}
}
}]);


I call it like this:

<dropdown ng-model="phs.phrases[row.index].posId"
items="phs.phrasePosShortNames">
</dropdown>


What I would like to do is to be able to call the directive and pass in a parameter called noButtonBorder. Then I would like the class "noBorder" to be added to the button if that parameter is passed.

Answer
scope: {
        ngModel: '=', // selected item
        items: '=',   // items to select from
        ngDisabled: '=',
        ngChange: '&',
        noButtonBorder: '='
    },
link: function (scope: any, element, attrs, ngModelCtlr) {
        // selection changed handler
        if(noButtonBorder){
       attrs.class="noBorder";
         }
        };
Comments