获取AngularJS

时间:2015-12-14 17:02:40

标签: jquery angularjs html5

如何在Angularjs中获取html5 data-attr值,并在同一个班级点击同一个函数。

就像在jquery中一样,我们点击一​​些类元素并获取当前元素data-num

我必须以有棱角的方式实现这一点。

如何获取多类元素并获取当前数据值($ this)?

<html ng-app="myApp">
    <head></head>
    <body ng-controller="mainController">
        <div ng-click="clicked()" data-num="1" class="same white">White</div>
        <div ng-click="clicked()" data-num="2" class="same green">Green</div>
        <div ng-click="clicked()" data-num="3" class="same red">Red</div>
        <div ng-click="clicked()" data-num="4" class="same white">White</div>
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
    <script>
        var myApp = angular.module('myApp',[]);
        myApp.controller('mainController',function($scope){
        $scope.clicked = function(){
        var id = angular.element('.same').scope();
        console.log(id);
        };
        });
    </script>
</html>

2 个答案:

答案 0 :(得分:4)

必要在函数

中传递事件
<div ng-click="clicked($event)" data-num="2" class="same green">Green</div>

在函数中获取$ event.target,获取DOM的JQUery并捕获数据attr

$scope.clicked = function($event){
     var id = $($event.target).data('num');
     console.log(id);
};

解决方案:JS FIDDLE

无论如何,我建议你不要用HTML存储数据,而是使用你的$ scope:

请考虑以下事项:

var app = angular.module('myApp',[]).controller('myController', function($scope)    {
  $scope.buttons = [
                    { num: 1, className: "class1", description: "desc 1" },
                    { num: 2, className: "class2", description: "desc 2" },
                    { num: 3, className: "class3", description: "desc 3" }
                   ];

  $scope.clicked = function(buttonNumber)
  {
    console.log(buttonNumber);
  }
})

HTML

<div ng-repeat="button in buttons" ng-click="clicked(button.num)" class="{{button.className}}">
    {{button.description}}
</div>

JS FIDDLE

答案 1 :(得分:0)

您不需要数据属性。

<div ng-click="clicked(1)" class="same white">White</div>
<div ng-click="clicked(2)" class="same green">Green</div>
<div ng-click="clicked(3)" class="same red">Red</div>
<div ng-click="clicked(4)" class="same white">White</div>


$scope.clicked = function(id){
    console.log(id);
};