Anthony Lee
Anthony Lee

Reputation: 243

How to get attribute value on click?

Hey guys I need to get tha data value of the button when I click on it. I tried in this way but it doesn't work..

var app = angular.module('myApp', []);

app.controller("myAppCtrl", function($scope, $attrs) {
    $scope.events = {}
    $scope.events.btnLoadMore = function() {
        var panel = $attrs.emptywidget;
        alert(panel);
    }
});

HTML

<html ng-app="myApp">
<head>
  <title></title>
</head>

<body ng-controller="myAppCtrl">
  <button data-emptywidget="#panel2" ng-click="events.btnLoadMore()">Click</button>
</body>
</html>

Upvotes: 0

Views: 1562

Answers (3)

Shawn C.
Shawn C.

Reputation: 6841

You can do a few different things.

1) You can pass in the data via the function so like

ng-click="events.btnLoadMore('#panel2')"

Then change your function to match so:

$scope.events.btnLoadMore = function(panel) {
    alert(panel);
}

2) You can pass in the data via the $event parameter

ng-click="events.btnLoadMore($event)"

Then change your function to match so:

$scope.events.btnLoadMore = function(clickEvent) {
    alert(clickEvent.target.attributes['data-emptywidget'].value);
}

3) You can just look at the arguments passed in to the function

$scope.events.btnLoadMore = function() {
    alert(arguments[0].target.attributes['data-emptywidget'].value);
}

Upvotes: 1

Andrew Church
Andrew Church

Reputation: 1391

You could use a combination of angular.element and passing in the $event source as well: http://jsfiddle.net/ahchurch/9USEv/1/

<div ng-controller="myAppCtrl">
    <button data-emptywidget="#panel2" ng-click="events.btnLoadMore($event)">Click</button>
</div>

var app = angular.module('myApp', []);

app.controller("myAppCtrl", function($scope, $attrs) {
    $scope.events = {}
    $scope.events.btnLoadMore = function($event) {
        console.log($event);
        var panel = angular.element($event.target).attr("data-emptywidget");
        console.log(panel);
    }
});

Upvotes: 1

PaReeOhNos
PaReeOhNos

Reputation: 4398

The only way you can access that data attribute would be through standard DOM access, which is not wise inside a controller. The $attrs variable you're passing into your controller also won't give you very much, as your controller doesn't directly related to anything (or at least it doesn't need to or shouldn't)

If you need to do something like that, then you could change your ng-click to something like

ng-click="events.btnLoadMore('#panel2')"

Then change the definition of your btnLoadMore function to take an argument. Alternatively you can write a directive that would be given that value, but that's more complex. But it depends what you want to do with it really. The above should work though

Upvotes: 2

Related Questions