Find / get parent in action using angularjs

I have a div structure with a 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 the values ​​of the data- * attributes from where I need it.

<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 the action know which event on which element triggered it? If so, how do I access this item, find the right parent?

+4
source share
2 answers

you can first send event [1] as a parameter to 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

+16
source

"Angular" DOM, . DOM ( ) , Angular.

, , ng-click, :

 <input type="button" value="Press me" class="button-one" ng-click="doSomething(2)" />

:

<input type="button" value="Press me" class="button-one" ng-click="doSomething({dataImage:2})" />

$scope, . - :

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];
  }; 
}]);

, DOM.

+2

All Articles