在函数中访问角度中单击对象的范围

时间:2015-10-17 10:39:38

标签: angularjs

我必须以角度访问单击对象范围的函数。我必须向控制台写入对象的id,但不通过click事件将对象传递给被调用的函数。
有人可以帮我解决问题吗? 下面是我到目前为止所取得的代码。

<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 个答案:

答案 0 :(得分:1)

您可以使用this关键字来引用当前的子范围,这样您就不必明确地将x传递给函数:

<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>

这是完整的例子:

&#13;
&#13;
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);
    }
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

尝试

<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>