刷新AngularJS中的可观察对象

Dav*_*vík 1 angularjs

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

我的控制器有一部分:

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

这是使用此控制器的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>
Run Code Online (Sandbox Code Playgroud)

如果我点击顶部的span类标题,控制器右键调用服务器并接收JSON数据.不幸的是,不要刷新与之相关的html.当我第二次点击时,html刷新第一次请求的数据.

pko*_*rce 6

您的模板没有更新,因为您正在使用jQuery进行xhr调用.那些调用被认为是"在AngularJS之外"的世界,所以AngularJS并不知道它们并且不知道它应该启动它自动刷新周期.

你会用优异的好得多$ http服务从AngularJS使XHR呼叫.你会写如下:

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

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

接下来,某些事情没有直接关系,但你真的没有广播事件来对事件作出反应click.写下来就足够了:

<span class="title" ng-click="myClickHandler()">
@*showMoreNotifications()*@
        Notifikace
</span>
Run Code Online (Sandbox Code Playgroud)

然后在你的控制器中:

$scope.myClickHandler = function(){
  //call $http here
}
Run Code Online (Sandbox Code Playgroud)