Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Add Elements to <li> dynamically

I am unable to populate list on clicking Add button. Problem is when I change the text field again, My List data gets changed (binding), how to avoid that?

HTML

<div class="control-group">
    <label class="control-label" for="projectManager">Project Manager(s)</label>
    <div class="row controls" >
        <input type="text" class="span3" placeholder="Manager name" ng-model="pm.name">
        <input type="text" class="span2" placeholder="Manager type" ng-model="pm.type">
        <button type="button" ng-click="addManagersForm()">&nbsp;&nbsp;Add&nbsp;&nbsp;</button>
    </div>
    <div class="row controls" >
        <ul><li ng-repeat="tPm in pms">{{tPm.name}}</li></ul>
    </div>
</div>

JS

app.controller('myContrl',["$scope", "$http", function($scope, $http) {
    $scope.pms = [];

    $scope.addManagersForm = function() {
        console.log($scope.pm);
        $scope.pms.push($scope.pm);
    };

}]);
like image 925
rohitpal Avatar asked Dec 02 '25 12:12

rohitpal


1 Answers

It happens because you are pushing the $scope.pm object into the array, and that object is binded in the form.

Just create a new object and you will be fine:

$scope.addManagersForm = function() {
    var pm = $scope.pm;
    $scope.pm = {}; // Do this to clean up the form fields
    $scope.pms.push(pm);
};
like image 200
Beterraba Avatar answered Dec 05 '25 03:12

Beterraba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!