AngularJS directive: Produce different HTML depending on $scope variable -


i started using angularjs , ran problem:

i have sidebar contains "action-buttons" - depending on active view, different buttons should visible.

my view-controller defines object looks follows:

$scope.sidebar.actionbuttons = [             {   icon: "plus",  label: "add",    enabled: true,  url: "customer.new" },             {   icon: "minus", label: "delete", enabled: false, action: function(){ alert("not implemented yet"); }}         ]; 

as can see, there 2 different kinds of action-buttons: either button changes view (url set customer.new), or button triggers arbitrary function (action set alert()).

each button type has generate different html, , i'm not able working.


after playing around several hours, here current (not-working) approach:

my sidebar uses following template-code generate buttons:

<ul class="nav" id="sidebar-action-buttons">     <action-button ng-repeat="button in actionbuttons" button="button"/> </ul> 

now, actionbutton directive has needs , should produce html depending on button type:

angular.module('myapp')     .directive('actionbutton', function($compile) {         function linker($scope, $element, $attrs){             var innerhtml = '';             $element.attr('ng-class', '{disabled: !button.enabled}');              if($scope.button.url) {                 $element.attr('ui-sref-active', 'active')                 innerhtml = '<a ui-sref="{{button.url}}">';             } else {                 innerhtml = '<a ng-click="button.action()">';             }             innerhtml += '{{button.label}}</a>';              $element.html(innerhtml).show();             $compile($element.contents())($scope);         }          return {             restrict: 'e',             replace: true,             scope: { button: "=" },             link: linker,             template: "<li></li>"         }     }); 

this generates correct content. problem here is, attributes placed on actionbutton element (in case ng-class='{disabled: !button.enabled}') not compiled.


how can directive produce different html depending on scope variables? correct approach doing this? how can compile newly added attributes?

by time ng-class added action-button element, digest on element. call $scope.$apply(), add ng-class each anchor element instead, there no need call $scope.$apply() again.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -