angularjs - Resetting form controls after action in Angular -
need bit of this. trying angular reset value of input box after add control invoked. kind of important when comes drop down select boxes. want able clear user has selected after option pushed collection.
i seems have issue user.fname
updating whatever added users
array it's related above.
also can see doing wrong 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, ' added'); } user = {}; //clear user }; }
ngmodel
try bind property given evaluating expression on current scope. if property doesn't exist on scope, created implicitly , added scope.
you not using scoped property in click action copy passed parameter. change user
$scope.user
in adduser
method
note: object comparison identify added users won't work create new objects never match. change different comparison method comparing 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 { // never match indexof() return -1 console.log($scope.user, ' added'); } $scope.user = {}; //clear user }; }
http://plnkr.co/edit/n5fxjdwrl42yrvwjsuur?p=preview
as ng-show question: $touched introduced in angularjs 1.3 , you're referencing angularjs 1.2.x in plunker code.
Comments
Post a Comment