Resetting form controls after action in Angular

87 Views Asked by At

Need a bit of help with this. I am trying to get Angular to reset value of my input box after add control is invoked. This is kind of important when it comes to drop down select boxes. I want to be able to clear what user has selected after the option is pushed to a collection.

I also seems to have an issue with user.fName updating whatever I previously added to the users array but it's probably related to the above.

Also can you see what I am doing wrong with ng-show?

html

<div ng-controller="UserController" name="form">
  <div ng-show="form.fName.$touched">Hello {{ user.fName }}</div>
  <input type="text" name="fName" ng-model="user.fName">
  <a ng-click="addUser(user)">Add</a>
    <br>
  <div ng-repeat="user in users">{{ user }}</div>
</div>

javascript

function UserController($scope) {
  //$scope.user = {
  //    fName: "Joe",
  //    lName: "Doe"
  //};
  $scope.users = [];
  $scope.addUser = function (user) {
    if($scope.users.indexOf(user) === -1){
      $scope.users.push(user);
    } else {
      // trigger error/notification message
      console.log(user, ' already added');
    }
    user = {}; //clear user
  };
}
1

There are 1 best solutions below

4
On BEST ANSWER

ngModel will try to bind to the property given by evaluating the expression on the current scope. If the property doesn't already exist on this scope, it will be created implicitly and added to the scope.

You are currently not using the scoped property in your click action but a copy that is passed as a parameter. Change user to $scope.user in your addUser method

Note: your object comparison to identify already added users won't work as you always create new objects that will never match. Change it to some different comparison method like comparing the fName properties.

html

<div ng-controller="UserController" name="form">
  <div ng-show="form.fName.$touched">Hello {{ user.fName }}</div>
  <input type="text" name="fName" ng-model="user.fName">
  <a ng-click="addUser()">Add</a>
    <br>
  <div ng-repeat="user in users">{{ user }}</div>
</div>

javascript

function UserController($scope) {
    $scope.users = [];
    $scope.addUser = function () {
        if($scope.users.indexOf($scope.user) === -1){
          $scope.users.push($scope.user);
        } else {
          // will never match as indexOf() will always return -1
          console.log($scope.user, ' already added');
        }
        $scope.user = {}; //clear user
    };
}

http://plnkr.co/edit/N5FXJdWRl42YrVwJsUuR?p=preview

As for your ng-show question: $touched was introduced in AngularJS 1.3 and you're referencing AngularJS 1.2.x in your Plunker code.