javascript - How to make an Add/Remove Array of strings in AngularJS -



javascript - How to make an Add/Remove Array of strings in AngularJS -

i need create info binding array of strings.. need array of directions.

i module way:

js

function shoppingcartctrl($scope) { $scope.directions = ["a", "b", "c"]; $scope.additem = function (item) { $scope.directions.push(item); $scope.item = ""; }; $scope.removeitem = function (index) { $scope.directions.splice(index, 1); }; }

html

<div ng-app> <div ng-controller="shoppingcartctrl"> <br /> <table border="1"> <thead> <tr> <td>directions</td> <td>remove item</td> </tr> </thead> <tbody> <tr ng-repeat="item in directions"> <td> <input ng-model="item" />{{$index}} </td> <td> <input type="button" value="remove" ng-click="removeitem($index)" /> </td> </tr> </tbody> </table> <br /> <table> <tr> <td> <input type="text" ng-model="item" /> </td> <td colspan="2"> <input type="button" value="add" ng-click="additem(item)" /> </td> </tr> <tr> <td>{{directions}}</td> </tr> </table> </div> </div>

everything works expected, have bug can't find. when seek modified values straight inputs, not allow. write , nil happened (this solved putting lastly version of angular in jsfiddle).

continue: can modify values, not updated in model. if can help me, awesome!!

you can see working in jsfiddle

solution #1: bind object's property instead of string

you shouldn't edit item directly, instead update attribute of item.

see working illustration here: http://jsfiddle.net/ray3whm2/15/

if want more info should read article: http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/

basically, never bind property itself, instead have dot in bindings, i.e. item.name instead of item. restriction due javascript , not angularjs.

solution #2: manually update model

if need to, can maintain array date manually using ng-change directive. see working illustration here: http://jsfiddle.net/ray3whm2/16/

javascript arrays angularjs data-binding

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -