在 ng-init 中声明多个值

因此,我想知道如何在一个 ng-init 中声明多个值,而不必创建一些奇怪的散列,这样我就需要始终专门访问这些散列。

所以基本上我希望

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

我是说我想避免

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

然而,合理的解释是:

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

好像不管用。

预料之中,谢谢

84073 次浏览

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"

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' "
 <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; };


});

I prefer wrap with object init variable:

<div ng-init="initObject = {initParam: 'initParamValue', anotherOne: 'value'}"></div>