2015-10-17 112 views
1

我必須以角度訪問被點擊對象範圍的函數。我必須向控制檯寫入對象的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> 

回答

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> 

這裏完成例如:

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>

+0

我沒想到是用 「這個」 訪問。 謝謝 – Laurianti

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>