Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find/Get parent element in action with angularjs

Tags:

angularjs

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?

like image 259
Eugene Avatar asked Nov 21 '13 13:11

Eugene


2 Answers

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

like image 161
Ben Avatar answered Sep 16 '22 19:09

Ben


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.

like image 38
Michal Charemza Avatar answered Sep 18 '22 19:09

Michal Charemza