我是 AngularJS 的新手,所以有时当我犯了一些明显的错误时,我仍然无法弄清楚我的代码出了什么问题。所以说,这是我的疑问:
HTML 代码:
<body ng-controller = "Ctrl">
<script id="Page6.html" type="text/ng-template">
<div class="list card" style="background-color: beige">
<div class="item item-icon-left">
<i class="icon ion-home"></i>
<input type="text" placeholder = "Enter display name" ng-model="user.nam">
</div>
<a ng-click = "saveedit(user)"<button class="button button-clear">SAVE DETAILS</button></a>
</div>
</script>
</body>
Controller .JS
.controller('Ctrl',function($scope,$rootScope,ContactService){
$rootScope.saveedit=function(user) {
ContactService.save({names: user.nam, image:"images.jpg"},ContactService.getid("Donkey"));
}
});
这是服务:
.service('ContactService', function () {
var items = [
{ id: 1, names: 'Dolphin', image: 'dolphin.jpg',}, { id: 2, names: 'Donkey', image: 'donkey.jpg'}, { id: 3, empid: 'FG2043', image: 'penguin.jpg'}];
var im = [{image: ''}];
var ctr=0;
var uid=3;
this.save = function (contact,id) {
ctr=0;
for (i=0;i<items.length;i++) {
if(items[i].id == id)
{
im[0].image= items[i].image;
ctr=100;
break;
}
}
uid = (uid+1);
contact.id = uid;
items.push(contact);
if (ctr==100 ) {
alert("in save putting the image");
items[contact.id].image = im[0].image; //doubt
alert("finished putting image");
}
}
//simply search items list for given id
//and returns the object if found
this.getid = function (name) {
for (i=0;i<items.length;i++) {
if (items[i].names == name) {
return (i+1);
}
}
}
//simply returns the items list
this.list = function () {
return items;
}
});
我面临的问题是:一切正常,除了一件事。在 ContactService 的 push() 函数中,我注释为//doubt 的行没有被执行。
“正在保存放置图像”之前的警报运行,但“已完成放置图像”警报则不会运行。有什么错误吗??
最佳答案
这里的问题是您使用从 1 开始的 id 来在索引从 0 开始的数组中导航。
要访问最近推送的元素,您应该这样做:
items[contact.id - 1].image = im[0].image;
但实际上您不需要访问该数组:items[contact.id - 1]
将返回您刚刚推送的对象,并且该对象已被变量 contact 引用
,所以你可以这样做:
contact.image = im[0].image;
关于javascript - JSON AngularJS 中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155818/