Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare multiple values in ng-init

So I'm wondering how I can declare multiple values within a single ng-init, without having to create some weird hash, that then I need to always access specifically.

so basically I would like

<div ng-init="a = 1, b = 2">{{a}}</div>

and I'm saying that I would like to avoid having to do

<div ng-init="unecessary_bs = {a: 1, b: 2}">{{unecessary_bs.a}}</div>

However the reasonable :

<div ng-init="a = 1, b = 2">{{a}}</div>

doesn't seem to work.

Anticipated Thanks

like image 661
Cosmin Avatar asked May 28 '14 19:05

Cosmin


People also ask

Can you initialize multiple variables at once?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

What is ng init?

The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.


2 Answers

Use a function, way more readable:

ng-init="init()"

And:

$scope.init = function() {
    $scope.a = 1;
    $scope.b = 2;
}

Or, if you must, separate inline variables with a semi-colon:

ng-init="a = 1; b = 2"
like image 89
tymeJV Avatar answered Oct 21 '22 02:10

tymeJV


Sometimes its not ideal to put the variables in a function. For example your backend is in express and you are rendering a file using jade.

With Express.js you can send local variables to the html. Angular can accept these variables with

ng-init=""

Using ";" one can have multiple variables

Example

ng-init=" hello='world'; john='doe' "  
like image 40
andrewoodleyjr Avatar answered Oct 21 '22 00:10

andrewoodleyjr