在我的下面的脚本中,我试图在ng-change事件中获取 li 元素的id,我将$ element注入到我的控制器中,现在我可以向li添加新的id但是
问题是,当我试图获取li的id时,不给了我 更新的值。它总是返回0.
以下是脚本:
var app = angular.module('myApp', []);
app.controller("baseCtrl", ['$scope',
function($scope) {
$scope.id = 0;
$scope.drivers = [];
}
]);
app.controller("childCtrl", ['$scope', '$element',
function($scope, $element) {
$scope.driver = {
name: "",
country: ""
};
$scope.change = function() {
if ($scope.driver.name && $scope.driver.country) {
var $id = $element.data('id');
console.log($id);
if ($scope.$parent.drivers.length > 0 && $id > 0) {
var $action = "update";
} else {
var $action = "insert";
}
if ($action == "update") {
$.each($scope.$parent.drivers, function(i, v) {
$scope.driver.id = $id;
if ($id == v.id) { // update
v[i] = $scope.driver;
}
});
} else if ($action == 'insert') { // insert data
//console.log($element);
$scope.driver.id = ++$scope.$parent.id;
$scope.$parent.drivers.push($scope.driver);
$element.attr('data-id', $scope.$parent.id);
}
//console.log($scope.$parent.id);
//console.log($scope.$parent.drivers);
}
};
}
]);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<body ng-app="myApp">
<div id="content" ng-controller="baseCtrl">
<ul>
<li ng-controller="childCtrl" data-id="0">
<input type="text" ng-model="driver.name" name="fname" ng-change="change()">
<select name="" id="" name="country_f" ng-model="driver.country" ng-change="change($event)">
<option value="india">India</option>
<option value="pakistan">Pakistan</option>
<option value="china">China</option>
</select>
</li>
<li ng-controller="childCtrl" data-id="0">
<input type="text" ng-model="driver.name" name="fname" ng-change="change()">
<select name="" id="" name="country_f" ng-model="driver.country" ng-change="change()">
<option value="india">India</option>
<option value="pakistan">Pakistan</option>
<option value="china">China</option>
</select>
</li>
<li ng-controller="childCtrl" data-id="0">
<input type="text" ng-model="driver.name" name="fname" ng-change="change()">
<select name="" id="" name="country_f" ng-model="driver.country" ng-change="change()">
<option value="india">India</option>
<option value="pakistan">Pakistan</option>
<option value="china">China</option>
</select>
</li>
<li ng-controller="childCtrl" data-id="0">
<input type="text" ng-model="driver.name" name="fname" ng-change="change()">
<select name="" id="" name="country_f" ng-model="driver.country" ng-change="change()">
<option value="india">India</option>
<option value="pakistan">Pakistan</option>
<option value="china">China</option>
</select>
</li>
</ul>
</div>
</body>
</html>
&#13;
任何帮助都会非常感激。提前致谢。