1

我正在使用 AngularJS,但找不到解决此问题的方法:

我的控制器有一部分:

$scope.$on('showMoreNotifications', function (event) {
    $.ajax({
        url: '/notifications',
        data: {
            notificationCount: 30
        },
        success: function (e) {
            $scope.notifications = e.Messages;
        }
    });
});

这是使用此控制器的html:

<div class="widget" id="widget-notifications" ng-controller="NotificationsCtrl">
    <span class="title" ng-click="$parent.$broadcast('showMoreNotifications')">@*showMoreNotifications()*@
        Notifikace
    </span>
    <div class="messages">
        <div ng-repeat="item in notifications" class="message-item type-{{item.Entity}}" data-id="{{item.AuditLogId}}">
            <span class="type"></span>
            <div class="description">
                <span class="date">{{item.Date}}</span> / {{item.Message}}
            </div>
        </div>
    </div>
</div>

如果我单击顶部的 span 类标题,控制器将正确调用服务器并接收 JSON 数据。不幸的是,不要刷新与之关联的 html。当我第二次单击时,html 会从第一个请求中刷新数据。

4

2 回答 2

6

您的模板没有更新,因为您正在使用 jQuery 进行 xhr 调用。这些调用被认为是“AngularJS 之外”的世界,因此 AngularJS 不知道它们,也不知道它应该启动它的自动刷新周期。

使用来自 AngularJS 的优秀$http 服务来进行xhr调用会更好。你会写这样的东西:

$http('/notifications', {params : {
            notificationCount: 30
        }}).success(function (e) {
            $scope.notifications = e.Messages;
        });

有一个类似的问题,答案有助于从 jQuery 的 $.ajax 迁移到 AngularJS $http:https ://stackoverflow.com/a/12131912/1418796

接下来,一些不直接相关的东西,但你真的不必广播事件来对事件做出反应click。写下就足够了:

<span class="title" ng-click="myClickHandler()">
@*showMoreNotifications()*@
        Notifikace
</span>

然后在你的控制器中:

$scope.myClickHandler = function(){
  //call $http here
}
于 2012-12-11T17:06:17.547 回答
1

现在我解决了我的问题......它需要适用于范围

像这样:

$.ajax({
    url: Escudo.UrlHelper.baseUrl + 'Widgets/Notifications/GetLastNotifications',
    data: {
        notificationCount: 30
    },
    success: function (e) {
        $scope.$apply(function () {
            $scope.notifications = e.Messages;
        });
    }
});
于 2012-12-11T16:59:06.663 回答