0

I am receiving dynamically data (in json format), and need to change the background images of buttons. Every buttons have ids so its easy to know, which button will be manupulated.

But I am having problem, when I try to manupulate the background-image of a button dynamically.

Example buttons:

<button id="1111_1111_c">Value1</button>
<button id="2222_2222_d">Value1</button>

I have tried to manupulate like so: (with JQuery)

var btnId = '2222_2222_d';
$('#' + btnId).css('background-image','url(images/btn_red.gif)');

but it happens nothing. If I try the same as pure JQuery, it works.

I know there is angular dom-updater or event to update the dom. But dont know how to do that.

Is there a solution with directives or using ng-class ?

Thank You!

Vural
  • 8,666
  • 11
  • 40
  • 57

1 Answers1

1

In Angular, we want to think about changing model/$scope properties, which will then automatically update the HTML view. (We don't want/need to work with IDs.) So declare a model property on the button that you want to change:

<button ng-class="button_1111_class" id=...>Value1</button>

(Above, button_1111_class is a property on $scope.) Then, when you get your data, modify your button_1111_class model data in your controller, e.g.:

$scope.button_1111_class = 'red_bg_image';  // red_bg_image is a CSS class you define

and your view should update automatically.

If you are getting your data outside AngularJS, you may need to wrap your model/$scope changes in $scope.$apply(): The view is not updated in AngularJS

Community
  • 1
  • 1
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • How can I call the button with a class, when they are gettin created dynamically? is it possible: $scope[button_1111_class] = 'red_bg_image'; ? Because I dont know the classname – Vural Oct 05 '12 at 09:23
  • What is getting created dynamically, buttons and/or the background images for those buttons? (I thought the buttons already existed and you were only changing the background images.) Can you create a fiddle showing your problem? http://pkozlowskios.wordpress.com/2012/08/12/using-jsfiddle-with-angularjs/ – Mark Rajcok Oct 05 '12 at 15:10