尝试在AngularJS中推送和数组时不是函数错误

时间:2015-12-25 20:25:03

标签: angularjs

这让我有些困惑,因为我确实正确地这样做了。的:

 submit()

功能正常,我通过在控制台中打印确认。但是我收到一个错误说:

Error

的index.html

<form ng-click="submit()" ng-controller="enterNameController">

        Name: <input type="text" ng-model="name" placeholder="Enter a new name." />
              <input type="button" value="Submit" id="submit" />

    {{name}}

</form>

  <div ng-controller="enterNameController">
    {{name.length}}
      <ul ng-repeat="n in name">
          {{n}}
      </ul>

  </div>

enterNameController.js

angular.module('myApp')
    .controller('enterNameController',['$scope',function($scope){
        $scope.name = [];
        $scope.submit = function(){

            if ($scope.name){
                $scope.name.push($scope.name);
                $scope.name = '';
                console.log("Inside submit function")
            }
        }

    }]);

2 个答案:

答案 0 :(得分:0)

你的控制器中有一个$ scope.name之类的数组,而视图中有$ scope.name之类的模型......你必须重命名数组;)

答案 1 :(得分:0)

angular.module('myApp')
    .controller('enterNameController',['$scope',function($scope){
        $scope.list = [];

        $scope.submit = function(){
            if($scope.list){
                $scope.list.push($scope.name);
                $scope.name = '';
            }

        };

    }]);