为什么AngularJS $范围无法正常工作?

时间:2016-04-30 09:51:24

标签: javascript angularjs

我是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函数中。

1 个答案:

答案 0 :(得分:2)

这是您的代码并正常运行。

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