Declare multiple values in ng-init
JavascriptAngularjsJavascript Problem Overview
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
Javascript Solutions
Solution 1 - Javascript
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"
Solution 2 - Javascript
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' "
Solution 3 - Javascript
I prefer wrap with object init variable:
<div ng-init="initObject = {initParam: 'initParamValue', anotherOne: 'value'}"></div>
Solution 4 - Javascript
<div ng-app="app">
<div ng-controller="TodoCtrl">
<ul>
<li ng-repeat="todo in todos" ng-init='initTodo = init(todo)'>
<span class="done-{{todo.done}}">{{todo.text}} |
and todo.text via init:{{initTodo}}</span>
</li>
</ul>
</div>
AND
var modulse = angular.module("app",[]);
modulse.controller("TodoCtrl", function ($scope) {
$scope.todos = [ {text:'todo1'}, {text:'todo2'}];
$scope.init = function (todo) { return todo.text; };
});