I have a div structure with button inside. i.e.
<div ng-app="example">
<div class="parent" data-image="1" ng-controller="ParentCtrl">
<div class="child" data-image="2">
<div style="overflow:hidden; margin-right:10px;">
<input type="button" value="Press me" class="button-one" ng-click="doSomething()" />
</div>
</div>
</div>
</div>
And I would like to get data-* attribute values from where I will need to.
<script type="text/javascript">
var Example = angular.module('example', []);
Example.controller('ParentCtrl', ['$scope', function($scope)
{
$scope.doSomething = function()
{
// want to get data-* attribute value from .parent/.child element
};
}]);
</script>
Does action know what event on what element triggered it? If so then how to access this element, to find needed parent?
first, you can send the event[1] as parameter of the ng-click function. Like this:
<input type="button" value="Press me" class="button-one" ng-click="doSomething($event)" />
and then in the function, using angular.element[2] get what you want. Like this:
Example.controller('ParentCtrl', ['$scope', function($scope)
{
$scope.doSomething = function(event)
{
var target = angular.element(event.target); //this target is a jQuery lite object
// now you can do what you want through the target
};
}]);
[1] http://docs.angularjs.org/api/ng.directive:ngClick
[2] http://docs.angularjs.org/api/angular.element
The "Angular" was of accessing the properties in the DOM would be to create your own directive. To access the DOM (and making assumptions about its structure) in the controller is seem as violating the separation of responsibilities that Angular encourages.
However, to avoid the complexity of creating a directive, you can pass parameters to the target of ng-click, like so:
<input type="button" value="Press me" class="button-one" ng-click="doSomething(2)" />
Including objects:
<input type="button" value="Press me" class="button-one" ng-click="doSomething({dataImage:2})" />
You can also store properties in the $scope variable, so you might only need to pass the index of an array, or the key of an object, to the function in the controller. So something like:
var Example = angular.module('example', []);
Example.controller('ParentCtrl', ['$scope', function($scope) {
$scope.things = [{something:123},{something:432];
$scope.doSomething = function(index) {
var thing = $scope.things[index];
};
}]);
should work as well, avoiding storing things in the DOM at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With