[英]pass dom object to processing function in angularjs
In the following code, I am trying to pass the table cell (as a DOM object) to the function, but this
doesn't mean the DOM object for the table cell, it appears that it refers to the $scope
. 在下面的代码,我试图通过表格单元格(如一个DOM对象)的功能,但是
this
并不意味着DOM对象的表格单元格,看来,它是指在$scope
。 Any idea how to do this? 任何想法如何做到这一点?
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr >
<td ng-click="dum();">ONE</td>
<td>TWO</td>
</tr>
<tr ng-repeat="x in names">
<td ng-click="dum(this);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
obj1 = "haha";
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {$scope.names = response.records;});
$scope.dum = function(x) { obj1 = x; console.log(x); }
});
</script>
</body>
</html>
You could, probably, do this: 您可能可以这样做:
In your HTML 在您的HTML中
<td ng-click="dum($event);">{{ x.Name }}</td>
In your Javascript 在您的Javascript中
$scope.dum = function(e) { obj1 = e.target; console.log(x); }
//e.target will be the clicked element.
I would not recommend accessing the DOM from a controller, but you can use the $event.target. 我不建议从控制器访问DOM,但是可以使用$ event.target。 Here's a plunker example: http://plnkr.co/edit/wFdnPJVa7BHOcvkPqNNT?p=preview
这是一个小例子: http ://plnkr.co/edit/wFdnPJVa7BHOcvkPqNNT?p=preview
angular.module('Test', [])
.controller('testCtrl', ['$scope', function($scope)
{
$scope.myFunc = function(e)
{
console.dir(e.target);
}
}]);
And the HTML 和HTML
<body ng-app="Test">
<div ng-controller="testCtrl">
<button ng-click="myFunc($event)">Click Me</button>
</div>
</body>
In angular, you should always code against your data. 角度而言,您应该始终根据数据进行编码。 Coding against the DOM is unnecessary in all but the most extreme edge cases, and when it is necessary, it's usually best done in a directive, where you can control how the rest of the angular app is updated.
除了最极端的情况外,在所有情况下都不需要对DOM进行编码,并且在必要时,通常最好在指令中完成,在该指令中您可以控制如何更新角度应用程序的其余部分。
In your case, you don't need to access the DOM, or the element, or even an event. 在您的情况下,您不需要访问DOM,元素或事件。 You already have all the information you need in order to handle your code with the data.
您已经拥有处理数据的代码所需的所有信息。
<tr ng-repeat="x in names">
<td ng-click="dum(x);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
and in the controller: 并在控制器中:
$scope.dum = function(x) { console.log(x); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.