1

I'm trying to add value in students array, but below code isn't working.

js code is --

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 code is --

<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 Answers 3

2

Your button and input are not included within the div ng-controller="ExampleController" scope.

<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>
Sign up to request clarification or add additional context in comments.

Comments

0

You need to push into $scope.students array, as there is no students array defined in the scope:

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

1 Comment

thanks for your response, i have tried with $scope.students.push(name); too but is not working, even function is not called
0
$scope.add = function(name) {

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

1 Comment

thanks, have tried with $scope.students.push(name); too but is not working, even function is not called

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.