1

I have to access a function to the scope of the clicked object in angular. I have to write to the console the id of the object, but without passing the object to the called function by the click event.
Could some one help me with my problem?
Below is the code what I have achieved so far.

<ul data-ng-app="myApp" data-ng-controller="myController">
 <li data-ng-repeat="x in names" data-ng-bind="x.title" data-ng-click="fnct(x)"></li>
</ul>
<script>
angular.module('myApp', []).controller('myController', function($scope) {
 $scope.names = [{id: 2345, title: 'title1'}, {id: 9876, title: 'title2'}];
 $scope.fnct = function(obj) {
  console.log(obj.id);
 }
});
</script>

2 Answers 2

1

You can use this keyword which will refer to current child scope so you don't have to pass x into function explicitly:

<ul data-ng-app="myApp" data-ng-controller="myController">
    <li data-ng-repeat="x in names" data-ng-bind="x.title" data-ng-click="fnct()"></li>
</ul>

Here is complete example:

angular.module('myApp', []).controller('myController', function($scope) {
    $scope.names = [{id: 2345, title: 'title1'}, {id: 9876, title: 'title2'}];
    $scope.fnct = function() {
        console.log(this.x.id);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<ul data-ng-app="myApp" data-ng-controller="myController">
    <li data-ng-repeat="x in names" data-ng-bind="x.title" data-ng-click="fnct()"></li>
</ul>

Sign up to request clarification or add additional context in comments.

1 Comment

I did not think was accessible by "this". Thank you
0

Try

<ul data-ng-app="myApp" data-ng-controller="myController">
 <li data-ng-repeat="x in names" data-ng-bind="x.title" data-ng click="fnct(x.id)"></li>
</ul>
<script>
 angular.module('myApp', []).controller('myController', function($scope) {
  $scope.names = [{id: 2345, title: 'title1'}, {id: 9876, title: 'title2'}];
  $scope.fnct = function(id) {
   console.log(id);
  }
 });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.