gpt4 book ai didi

javascript - 更新 ng-repeat 数组

转载 作者:行者123 更新时间:2023-11-29 19:29:16 26 4
gpt4 key购买 nike

我读过很多这样的问题,但出于某种原因还没有找到我的代码无法正常工作的原因。

目标是让页面加载由 ng-repeat 加载的项目列表,这工作正常,但是当用户执行功能时,让 ng-repeat 数组替换为另一个相同结构的数组。是通过http获取的。

代码是这样的

// in HomeController

$scope.content = {
items: [ {
title: "hi!"
} ]
}

$scope.search = function() {
if ( $scope.query == '' )
return $scope.content = null

$http
.get( '/api/search', { params:
{ terms: $scope.query }
} )
.success( function ( results ) {
console.log( results)
$scope.content.items = results
})
.error( function ( error ) {
$flash.error = error
})
}

然后

// in the HTML

<div ng-controller="HomeController" class="list-container">

<div class="panel panel-item" ng-repeat="item in content.items">
<h2 ng-bind="item.title"></h2> // ... etc

然后在别处有一个触发search()ng-change。我知道 http.get 有效,因为我在控制台中看到了它。但从外观上看,它不会更新 ng-repeat 的主要来源,甚至不会更新范围。


如果这个 Controller 嵌套在另一个 Controller 中是否相关?

最佳答案

解决方案

您遇到的问题是这一行:

return $scope.content = null;

因为此时您销毁了您的对象 $scope.content 这意味着它没有任何从属属性或任何东西。因此,当您之后尝试为其属性赋值时,该属性在 null 变量上不存在,您会收到运行时错误:

Cannot set property 'items' of null

因此,如果您将上行更改为

return $scope.content.items = null;

一切正常。这样您的 content 就不会被破坏,它只是为其内部属性重新分配一个新值。

或者您也可以保留初始行,但之后将分配更改为

$scope.content = {
items: result
};

因此,当您获得结果时,您会重新创建之前可能已被销毁的整个 content 对象(分配给 null)。

但我个人建议您将上面的问题代码行更改为:

$scope.content.items = [];
return null; // change to whatever return value seems appropriate

这将使您的属性保持最初的 Array 状态。你只需清空它。有时最好将 Javascript 视为一种强类型语言,并且不要执行会破坏强类型语言的代码。

Here's an example将两个工作版本与您正在使用但不工作的版本进行并排比较

关于javascript - 更新 ng-repeat 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29026044/

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