简体   繁体   English

如何正确使用ng-class或angular.element?

[英]How to use ng-class or angular.element correctly?

I am receiving dynamically data (in json format), and need to change the background images of buttons. 我正在动态接收数据(JSON格式),并且需要更改按钮的背景图像。 Every buttons have ids so its easy to know, which button will be manupulated. 每个按钮都有ID,因此易于理解,将操作哪个按钮。

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) 我试图这样操纵:(使用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. 如果我尝试与纯JQuery相同,它将起作用。

I know there is angular dom-updater or event to update the dom. 我知道有角度dom-updater或事件来更新dom。 But dont know how to do that. 但是不知道该怎么做。

Is there a solution with directives or using ng-class ? 有指令或使用ng-class的解决方案吗?

Thank You! 谢谢!

In Angular, we want to think about changing model/$scope properties, which will then automatically update the HTML view. 在Angular中,我们想考虑更改model / $ scope属性,然后将自动更新HTML视图。 (We don't want/need to work with IDs.) So declare a model property on the button that you want to change: (我们不想/不需要使用ID。)因此,在要更改的按钮上声明一个模型属性:

<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, eg: (上面,button_1111_class是$ scope的属性。)然后,当您获取数据时,请在控制器中修改button_1111_class模型数据,例如:

$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 如果您收到您的数据外AngularJS,你可能需要包装在$范围模型/ $范围变更申请$(): 视图不更新AngularJS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM