gpt4 book ai didi

javascript - $watch 触发 promise "then"数组但不是值

转载 作者:行者123 更新时间:2023-11-30 12:37:55 25 4
gpt4 key购买 nike

我是 Angular 的新手,我看到发生了以下奇怪的问题,我不确定为什么。我有一个简单的 Controller ,它在作用域上有 2 个属性——“sentences”和“countVal”,它们显示在我的 html 页面的顶部。

我有一个工厂“ModelState”,它保存我的服务“UpdatingService”填充的数据。

我看到的奇怪问题是 ModelState.values.push(data);导致数组长度值变为 1,但计数值不增加。 TestCtrl 中的 $watch 也不会记录到控制台。我确定我做错了什么,但我不知道是什么。这是我的 html(内联脚本)。非常感谢。

<!doctype>
<html ng-app="testApp">

<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.15/angular.js"></script>
</head>

<body ng-controller="TestCtrl">

<p>Array length : {{ sentences.length }}</p>
<p>Count value : {{ countVal }}</p>
<br>

</body>

<script>
var testApp = angular.module('testApp', []);

testApp.controller('TestCtrl', function($scope, ModelState, UpdatingService) {

$scope.sentences = ModelState.values;
$scope.countVal = ModelState.countVal;

$scope.$watch("countVal", function(newValue, oldValue){
console.log(newValue," ",oldValue);
}, true);
});

testApp.factory('ModelState', function(){
return {
values : [],
countVal : 0
};
});

testApp.service("UpdatingService", function($http, $timeout, ModelState, $q){
var service = {

getData:function(){
var promise = $http.get("http://baconipsum.com/api/?type=meat-and-filler");

promise.success(function(data){
ModelState.values.push(data);
ModelState.countVal++;
});

return promise;
}
};

service.getData();

return service;
});

</script>

</html>

最佳答案

当您在 Controller 中写入时:

$scope.sentences = ModelState.values;
$scope.countVal = ModelState.countVal;

您将 reference 分配给 sentences 数组 - 从现在开始 ModelState$scope 将引用到Array

的相同实例

并且您正在将 value 分配给 countVal 属性 - 从现在开始 ModelState$scope 指向 <Number

的 strong>2 个不同的实例

然后,当您push 新项目到sentences 时,它的length 变化会反射(reflect)在 View 中,但是$scope.countVal 没有更改,因为您只更改了 ModelState.countVal 的属性。

解决这个问题的一种方法是简单地分配 $scope.ModelState = ModelState 并直接在 View 中使用它的属性:

<p>Array length : {{ ModelState.sentences.length }}</p>
<p>Count value : {{ ModelState.countVal }}</p>

另一种方法是使用范围方法来访问 ModelState 值,如下所示:

$scope.sentenecesLength = function(){
return ModelState.sentences.length;
};
$scope.countVal = function(){
return ModelState.countVal;
};

<p>Array length : {{ sentenecesLength() }}</p>
<p>Count value : {{ countVal() }}</p>

关于javascript - $watch 触发 promise "then"数组但不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25465915/

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