angularjs - NG-init 通过函数

标签 angularjs angularjs-directive angularjs-ng-init

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

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

相关文章:

javascript - 为什么错误angularjs Error : $compile:tpload Error Loading Template

javascript - Angular Directive(指令) : Adding ng-class directive at compile time on existing template element

javascript - ng-init 没有在我的 Angular 应用程序中的选择中设置我的默认类别

javascript - angularjs指令使用 Controller 作为vm而不是作用域

javascript - 如何 $setdirty 到单个输入

javascript - ng-repeat 拼接显示双

javascript - angularjs中指令的动态模板

angularjs - 如何在页面加载时将数据加载到范围

javascript - ng-click 在 ag-grid 标题模板内

angularjs - 当作为 Angular 指令实现时,Highcharts 跨越引导列宽度