我是AngularJS的新手,我想创建一个数组并通过register
函数将其发布到服务器,这里是控制器代码:
root.controller('mainController', function($scope) {
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data -> Array [ "1", "2", "3", "4", "1" ]
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array -> Array [ ]
};
});
这是HTML代码和指令:
<div class="container" ng-controller="mainController">
<a ng-click="register()"></a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add</a>
</div>
</div>
当我想调用register
函数时出现问题,它给了我一个空数组而不是数组元素,而它不会发生在addItem
函数中。
答案 0 :(得分:2)
这是您的代码并正常运行。
var app = angular.module("testApp", []);
app.controller('testCtrl', function($scope){
$scope.products = [{id:1},{id:2},{id:3},{id:4}];
$scope.lineItems = [];
$scope.addItem = function (id) {
$scope.lineItems.push(id);
console.log($scope.lineItems);
// gives me right data
};
$scope.register = function () {
// post data to server
console.log($scope.lineItems);
// gives me an empty array
};
});
&#13;
<div ng-app="testApp" ng-controller="testCtrl">
<a ng-click="register()">Register</a>
<div ng-repeat="product in products">
<a class="btn" ng-click="addItem(product.id)">Add : {{product.id}}</a>
</div>
</div>
&#13;