gpt4 book ai didi

javascript - 更改 $scope 属性并观察变化

转载 作者:行者123 更新时间:2023-11-28 15:35:30 25 4
gpt4 key购买 nike

好吧,我刚接触 AngularJS 1 天,所以这必须是超基础的(我希望不是一个对 AngularJS 工作原理一无所知的人 - 我承认 MVC 并不是我的专长,但无论如何......) .

我的代码:

var PP = angular.module('PP', []);

PP.controller('documentController', function ($scope) {
$scope.documents = [
{
'filename': 'Untitled-1',
'content': 'Content-1'
},
{
'filename': 'Untitled-2',
'content': 'Content-2'
},
{
'filename': 'Untitled-3',
'content': 'Content-3'
},
];
});

所以,我声明了一个模块(PP),其中有一个 Controller (documentController)和一个属性(?)(documents) >).

<小时/>

所以,我有两个问题:

  • 我如何(欢迎任何可能的方式)以编程方式访问和更改 documents 数组? (插入/删除/等)
  • 如何设置一个在数组更改时触发的事件,例如已插入元素?

最佳答案

访问数组

在你的 Controller 中,你只需使用:

$scope.documents.push({filename: 'Another', content: 'Document'})

您可以在任何 Controller 函数中执行此操作,因为数组是作用域中共享的变量。由于它在范围内,您也可以在 View 中访问它,如下所示:

<button ng-click="documents.push({filename: 'Another', content: 'Document'})">
Add document
</button>

通常,我会在 Controller 中为要在 View 中使用的此行为定义便利函数,但在这个简单的示例中,应该这样做。

检测数组中的变化

要监视集合中的更改,您可以使用$scope.$watchCollection:

$scope.$watchCollection('documents', function(newDocuments, oldDocuments) {
// do something when the documents array changes
});

有关 $watch$watchCollection 之间的比较,请参阅 Scope $watch() vs. $watchCollection() In AngularJS .

请注意,监视可能很棘手:正确检测更改并不总是那么简单,根据我的经验,这些函数被调用的频率比应有的要高。

根据您的用例,您可能不需要任何 watch (Angular 提供了多种方法来对变化使用react,而无需使用单个 watch ),并且 you probably shouldn't use $watch in your controllers无论如何。

关于javascript - 更改 $scope 属性并观察变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25737399/

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