我在函数中有一个数组arr,我想返回$ scope.notifications,所以我可以在Ionic Framework的HTML中使用它。 我需要通过一个函数来完成它,所以我可以在稍后返回之前对数组执行几个操作。 我的控制器:
.controller('notificationsCtrl', function($scope) {
$scope.notifications = function(){
var arr = [
{user:"misterx", name:"Mister X", action:4, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
{user:"misterx", name:"Mister X", action:2, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
{user:"ladyx", name:"Lady X", action:1}
];
return arr;
}
})
HTML:
<ion-item ng-repeat="msg in notifications" class="item-text-wrap">
<div class="row">
<div class="col-80">
<strong>{{msg.name}}</strong> (<em>@{{msg.user}}</em>) {{msg.action}}.
</div>
<div class="col-20">
<img src="{{msg.image}}" style="border-radius: 50px; width: 100%">
</div>
</div>
</ion-item>
当我直接将通知作为数组传递时,没有函数,它可以工作。我在这里做错了什么?
答案 0 :(得分:2)
使用ng-repeat="msg in notifications"
尝试重复函数本身,而不是其返回值。您想要调用该函数:
<ion-item ng-repeat="msg in notifications()">
https://jsfiddle.net/dj1gpjb8/
我应该指出,这种方法存在性能问题:该函数将被频繁调用,因为Angular无法预测函数的结果是否会发生变化。最好将通知作为普通数组嵌入到作用域中;以后修改该数组的任何内容都会自动触发组件使用新值重新呈现:
$scope.notifications = [{
user: "misterx",
name: "Mister X",
//...
}];
$scope.addNotification = function() {
$scope.notifications.unshift({
user: "newguy",
name: "New Guy"
});
// angular will notice that notifications[] has changed, and re-render the component on the next $digest
};
答案 1 :(得分:-2)
以下代码是最新的,因此无需使用函数返回JSON格式
.controller('notificationsCtrl', function($scope) {
$scope.notifications = [
{user:"misterx", name:"Mister X", action:4, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
{user:"misterx", name:"Mister X", action:2, image: "https://www.holidaycheck.de/mediaproxy?target=hcaHR0cDovL3d3dy5ob3RlbC5kZS9tZWRpYS9ob3RlbC9waWN0dXJlcy8zMzQvMzM0MTIzL0V4dGVyaW9yXzYzNTkyNzk5NDMyODQ1OTAwMi5qcGc%3D"},
{user:"ladyx", name:"Lady X", action:1}
];
}
})