通过函数 Ng-init [英] Ng-init via function

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

问题描述

如您所知,可以按如下方式初始化对象:

<div ng-init="friends = [{name:'John', phone:'555-1276'},{姓名:'玛丽',电话:'800-BIG-MARY'},{姓名:'迈克',电话:'555-4321'},{姓名:'亚当',电话:'555-5678'},{姓名:'朱莉',电话:'555-8765'},{姓名:'朱丽叶',电话:'555-5678'}]"></div>

是否可以通过函数定义类似的对象:

我的目标实际上是从 API 中获取对象并通过 ng-repeat 将它们显示在列表中

解决方案

文档ng-init 将采用任何表达式.所以是的,只要关联的作用域定义了一个名为 init() 的函数,你就可以做你想做的事情(我也为了好玩而验证了它).

请注意,文档说 ng-init 实际上仅用于 ng-repeat 内的别名属性:

<块引用>

ngInit 唯一合适的用于别名特殊属性的用法ngRepeat,如下面的演示所示.除了这种情况,你应该使用控制器而不是 ngInit 来初始化作用域上的值.

最后,请注意,您可以在创建控制器时简单地初始化变量.所以根本没有必要使用 ng-init .例如:

var myApp = angular.module('myApp', []);myApp.controller('myController', ['$scope', function($scope){$scope.init = function() {$scope.a = '苹果';$scope.b = '蜜蜂';$scope.c = '斑马';};//每个控制器实例化运行一次$scope.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()">

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

解决方案

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).

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

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.

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天全站免登陆