在AngularJs中获取和设置一个元素的类 [英] Get and Set class of an element in AngularJs

查看:121
本文介绍了在AngularJs中获取和设置一个元素的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将ng-click添加到我的图标中,如下所示:

 < img src =images / customer_icon .pngclass =customerng-click =processForm($ event)> 

以下是js-file。

  var app = angular.module('myapp',[]); 
app.controller('mycontroller',function($ scope){
$ scope.processForm = function(obj){
var elem = angular.element(obj);
alert(Current class value:+ elem.getAttribute(class));
};
});

我收到elem.getAttribute不是函数错误。试图将class切换到ng-class,我遇到了另一个问题:ng-class不能被我的css文件识别。



有没有什么办法可以直接获取/设置class属性?

解决方案

var app = angular。 module('myapp',[]); app.controller('mycontroller',function($ scope){$ scope.processForm = function(event){var element = angular.element(event.target); // Old Class console.log(OLD CLASS:+ element.attr('class')); element.removeClass('customer')。addClass(newClass); //新类console.log(NEW CLASS:+ element.attr('class'));};});

< script src =https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js>< / script>< div ng-app = myappng-controller = mycontroller>< img src =http://placehold.it/200x100class =customerng-click =processForm($ event)>< / div>



更多信息 angular.element


I've added the ng-click to my icon like this:

<img src="images/customer_icon.png" class="customer" ng-click="processForm($event)">

And here's the js-file.

   var app = angular.module('myapp', []);
    app.controller('mycontroller', function($scope) {
        $scope.processForm = function(obj) {
            var elem = angular.element(obj);
            alert("Current class value: " + elem.getAttribute("class"));
       };
    });

I'm getting the "elem.getAttribute is not a function" error. Trying to switch "class" to "ng-class", i faced another problem: "ng-class" is not recognised by my css files.

Is there any way I can get/set the "class" attribute directly?

解决方案

Try following snippet.

var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope) {
    $scope.processForm = function(event) {
      var element = angular.element(event.target);
      //Old Class
      console.log("OLD CLASS : " + element.attr('class'));
      element.removeClass('customer').addClass("newClass");
      //New Class
      console.log("NEW CLASS : " + element.attr('class'));
    };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycontroller">
<img src="http://placehold.it/200x100" class="customer" ng-click="processForm($event)">
</div>

More information angular.element

这篇关于在AngularJs中获取和设置一个元素的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆