0

I want to pass a value from the controller to the directive but the directive in the view can be overridden.

Example Controller

    var controllers = angular.module('Project.Controllers.ActionBarCtrl', []);
    controllers.controller('ActionBarCtrl', ['$scope','$rootScope', 
        function($scope, $rootScope){
        $scope.buttonColor = 'red' 
}]);

Then in my view there are two possible ways to load

<div my-button button-color='green'></div>

or

<div my-button></div>

in the directive i want to pass in the button color (green in the first div and the default of red in the second div), here is my directive

sharedDirectives.directive('myButton', function () {
    return {
        restrict: 'A',
        transclude: true,
        scope: {
            'buttonColor': '@'
        },
        template: '<div>' +
                    '<button class="uifw-frm-button small {{buttonColor}}" ng-click="showHideInner()">
                 + </div>

I can get it to work with the first div and populating the buttonColor property with the value of green but when i leave it out and want to return red I get the value as undefined.

2 Answers 2

1

using ng-class

template: '<div>' +
            '<button class="uifw-frm-button small" ng-class="{'red':!buttonColor,buttonColor:buttonColor}" ng-click="showHideInner()">
         + </div>
Sign up to request clarification or add additional context in comments.

Comments

1

try to add the compile function to your directive:

compile: function(element, attrs)
{
   if (!attrs.buttonColor) { attrs.buttonColor= 'red'; }
}

or in the controller of the directive:

controller: function($scope){
    $scope.buttonColor = $scope.buttonColor || 'red';
  }

ok, the one with compile works:

http://jsfiddle.net/eYJqC/

1 Comment

Thanks for this answer, i gave it a try however more functionality was needed after the button click and the 'compile: ...' stoped any further code from executing. So the answer that i used is the one I chose above. I dont know what if i was doing something wrong after the compile, but this didnt allow for any other code to run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.