gpt4 book ai didi

angularjs - NG-init 通过函数

转载 作者:行者123 更新时间:2023-12-02 21:59:22 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

documentation表示 ng-init 将采用任何表达式。所以是的,只要关联的作用域定义了一个名为 init() 的函数(我也为了好玩而验证了它),您就可以执行上面您想要的操作。

请注意,文档说 ng-init 实际上仅用于 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.

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

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();

}]);

关于angularjs - NG-init 通过函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20603869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com