gpt4 book ai didi

javascript - $watchCollection 未更新页面上的数组长度

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

我正在尝试为用户的警报数量设置一个计数器。如果我 console.log $scope.alerts 和 $scope.count,我可以看到两者都在更新,但是使用 {{alerts.length}} 或 {{count}} 作为 #msgCount 的值只会给我pageLoad 上的初始计数,并且当数组长度更改时不会更新。我做错了什么?

我的 Controller :

myApp.controller('globalAlerts', ['$scope', '$http', function ($scope, $http) {
$scope.alerts = [{
"type": "warning",
"msg": "This is a generic alert. It is best suited for one or two line messages."
},
{
"type": "danger",
"msg": "<strong>Past Due!</strong> You have an invoice <a class=\"invoice-link\" href=\"\">192607</a> that is past due. <a href=\"invoices.html\">View all invoices.</a>"
},
{
"type": "success",
"msg": "This green alert indicates something positive occurred. Doesn't that make you feel happy?"
},
{
"type": "info",
"msg": "This blue alert is another generic warning usually used to inform. Isn't it soothing?"
}
];
$scope.$watchCollection('alerts.length', function() {
return $scope.alerts.length;

}, true);
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};



$scope.dynamicPopover = {
templateUrl: 'partials/alerts/globalAlerts.html',
title: 'Recent Alerts'
};

}]);

和标记:

<div id="upperNav" ng-controller = "globalAlerts">
<a class="btn btn-link" id="msg" popover-placement="bottom" uib-popover-template="dynamicPopover.templateUrl" popover-title="{{dynamicPopover.title}}" >
<div class="badge badge-warning" id="msgCount">{{alerts.length}}</div>
ALERTS</a></div>

使用弹出框标记:

<div id="alertCntr" ng-controller = "globalAlerts">
<uib-alert ng-show="alerts.length" ng-repeat="alert in alerts track by $index" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</uib-alert>
<p ng-hide="alerts.length">You ain't got no more alerts, kid!</p>
</div>

最佳答案

对于其他用户:

HTML 指定每个 block 都有自己的 Controller 。这意味着两个 Controller 是独立的,不知道彼此的警报数组何时被触摸。

最简单的解决方案是嵌套 HTML,以便它们共享一个 Controller :

<div id="upperNav" ng-controller = "globalAlerts">
<a class="btn btn-link" id="msg" popover-placement="bottom" uib-popover-template="dynamicPopover.templateUrl" popover-title="{{dynamicPopover.title}}" >
<div class="badge badge-warning" id="msgCount">{{alerts.length}}</div>
ALERTS</a>
<div id="alertCntr">
<uib-alert ng-show="alerts.length" ng-repeat="alert in alerts track by $index" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</uib-alert>
<p ng-hide="alerts.length">You ain't got no more alerts, kid!</p>
</div>
</div>

编辑:

更新了 plnkr,它完全符合您的要求:http://plnkr.co/edit/AIwGi7eIzilsGGL7Us3G?p=preview

关于javascript - $watchCollection 未更新页面上的数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35872470/

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