简体   繁体   English

在 ng-init 中声明多个值

[英]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.所以我想知道如何在单个 ng-init 中声明多个值,而不必创建一些奇怪的哈希,然后我需要始终专门访问。

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期待感谢

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.例如,您的后端在 express 中,并且您正在使用 jade 渲染文件。

With Express.js you can send local variables to the html.使用 Express.js,您可以将局部变量发送到 html。 Angular can accept these variables with Angular 可以接受这些变量

ng-init=""

Using ";"使用 ”;” one can have multiple variables一个可以有多个变量

Example例子

ng-init=" hello='world'; john='doe' "  

我更喜欢用对象初始化变量包装:

<div ng-init="initObject = {initParam: 'initParamValue', anotherOne: 'value'}"></div>
 <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; };

  });

只需用半冒号{{a}}代替昏迷即可

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM