Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an Array with AngularJS's ng-model

I'm trying to create an array holding telephones, i have this code

<input type="text" ng-model="telephone[0]" /> <input type="text" ng-model="telephone[1]" /> 

But i can't access $scope.telephone

like image 949
DelGiudice Avatar asked Feb 07 '14 15:02

DelGiudice


People also ask

What is NG-model in AngularJS?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

Is AngularJS an array?

isArray() Function in AngularJS is used to return TRUE if the reference is an array and FALSE if it is not an array. Syntax: angular. isArray(value);

What is difference between ng-model and Ng bind?

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable. Save this answer.

Can we use filter in NG-model?

By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a filter.


2 Answers

First thing is first. You need to define $scope.telephone as an array in your controller before you can start using it in your view.

$scope.telephone = []; 

To address the issue of ng-model not being recognised when you append a new input - for that to work you have to use the $compile Angular service.

From the Angular.js API reference on $compile:

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

// I'm using Angular syntax. Using jQuery will have the same effect // Create input element var input = angular.element('<div><input type="text" ng-model="telephone[' + $scope.inputCounter + ']"></div>'); // Compile the HTML and assign to scope var compile = $compile(input)($scope); 

Have a look on JSFiddle

like image 181
lnoogn Avatar answered Oct 12 '22 14:10

lnoogn


It works fine for me: http://jsfiddle.net/qwertynl/htb9h/

My javascript:

var app = angular.module("myApp", []) app.controller("MyCtrl", ['$scope', function($scope) {     $scope.telephone = []; // << remember to set this }]); 
like image 38
qwertynl Avatar answered Oct 12 '22 14:10

qwertynl