Reputation: 2613
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.
Upvotes: 0
Views: 1762
Reputation: 2200
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:
Upvotes: 1
Reputation: 3462
using ng-class
template: '<div>' +
'<button class="uifw-frm-button small" ng-class="{'red':!buttonColor,buttonColor:buttonColor}" ng-click="showHideInner()">
+ </div>
Upvotes: 1