在http://www.w3schools.com/angular/tryit.asp?filename=try_ng_repeat_object
中而不是
<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
是否存在一种语法来引用在ng-init中其他地方声明的外部变量(并且未在angularjs控制器中声明),因为这个不起作用:
<script>
var myNames = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]
</script>
<div ng-app="" ng-init="names=myNames">
我知道这是不好的做法,但我也使用另一个框架,并且不想复制变量的内容。它只是用于原型设计而不是真正的应用程序的代码。
否则如果我使用ng-init初始声明,我可以从另一个脚本变量中引用它吗?
答案 0 :(得分:1)
由于以下原因,它无法正常工作
当出现这种情况时,最佳做法是使用控制器。
根据聊天
中的讨论进行了更新<body>
<script>
var myNames = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}];
var app = angular.module('myApp',[]);
app.controller('myController',function($scope){
$scope.names=window.myNames;
});
</script>
<div ng-app="myApp" ng-controller="myController">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names">{{ x.name + ', ' + x.country }}</li>
</ul>
</div>
</body>