通过功能NG-INIT [英] Ng-init via function

查看:203
本文介绍了通过功能NG-INIT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如你所知,这是可能的初始化对象如下:

As you know, it is possible to initialize objects as follows:

<div ng-init="friends = [{name:'John', phone:'555-1276'},
                         {name:'Mary', phone:'800-BIG-MARY'},
                         {name:'Mike', phone:'555-4321'},
                         {name:'Adam', phone:'555-5678'},
                         {name:'Julie', phone:'555-8765'},
                         {name:'Juliette', phone:'555-5678'}]"></div>

是否有可能定义类似这样的,而是通过一个函数对象:

Is it possible to define object similar like this but via a function:

<div ng-init="init()">

我的目的实际上是从一个API通过NG-重复服用的对象,并将其显示在列表中。

My aim is actually taking the objects from an API and show them in a list via ng-repeat

推荐答案

借助文档 NG-INIT 将采取任何前pression。所以,是的,你可以做你想做上面,只要相关的范围定义了一个调用的函数是什么的init()(我也验证了它的乐趣)。

The documentation says ng-init will take any expression. So yes, you can do what you want above as long as the associated scope defines a function called init() (and I also verified it for fun).

请注意,该文件说, NG-INIT 真的只打算用于内部的 NG-重复

Note that the documentation says that ng-init is really only intended to be used for aliasing properties inside of an ng-repeat:

唯一的适当使用ngInit的混叠的特殊属性
  ngRepeat,如在下面的演示。除了这种情况下,你应该使用
  控制器而不是ngInit在一个范围内初始化值。

The only appropriate use of ngInit for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

最后,请注意,你可以简单地初始化变量,创建控制器时。所以真的没有必要使用 NG-INIT 可言。例如:

Finally, note that you can simply initialize your variables when the controller is created. So there's really no need to use ng-init at all. For example:

var myApp = angular.module('myApp', []);

myApp.controller('myController', ['$scope', function($scope){

  $scope.init = function() {
    $scope.a = 'Apples';
    $scope.b = 'Bees';
    $scope.c = 'Zebras';
  };
  // runs once per controller instantiation
  $scope.init();

}]);

这篇关于通过功能NG-INIT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆