无法在angularjs中添加字符串数组中的值?

时间:2015-08-02 11:00:18

标签: html angularjs

我正在尝试在students数组中添加值,但下面的代码无效。

js代码是 -

angular.module('formExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.students=[
        'Scarlett Johansson','Jennifer Lawrence','Emma Stone','Kristen Stewart'
      ];  

      $scope.add = function(name){
        $scope.students.push(name);
      };
}]);

html代码是 -

<body ng-app="formExample">
  <div ng-controller="ExampleController">
    <p ng-repeat="stud in students">
      {{stud}}
    </p>
  </div>
  <input type='text' ng-model="name"/>
  <button ng-click="add(name);">add</button>
</body>

3 个答案:

答案 0 :(得分:2)

您的buttoninput未包含在div ng-controller="ExampleController"范围内。

<body ng-app="formExample">
  <div ng-controller="ExampleController">
    <p ng-repeat="stud in students">
      {{stud}}
    </p>

    <input type='text' ng-model="name"/>
    <button ng-click="add(name);">add</button>
  </div> <!-- close div here -->
</body>

答案 1 :(得分:0)

您需要推入$scope.students数组,因为范围中没有定义students数组:

$scope.add = function(name) {
    $scope.students.push(name);
};

答案 2 :(得分:0)

$scope.add = function(name) {

   $scope.students.push(name);//
};