1

I'm using AngularJS and can't find way to resolve this Issue:

there is part from my controller:

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

and here is html which using this controller:

<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>

If I click on span class title on top, controller right call to server and receives JSON data. Unfortunately dont refresh html which is associated with it. When I click second time, html refresh data from first request.

David Slavík
  • 1,132
  • 1
  • 14
  • 23

2 Answers2

6

Your template is not updating since your are making xhr calls using jQuery. Those calls are considered "outside of AngularJS" world so AngularJS is not aware of them and doesn't know that it should start it automatic refresh cycle.

You would be much better using excellent $http service from AngularJS to make xhr calls. You would write something like:

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

There was a similar question where the answer helps migrating from jQuery's $.ajax to AngularJS $http: https://stackoverflow.com/a/12131912/1418796

Next, something not directly related, but you really don't have to broadcast events to react on the click event. It would be enough to write:

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

and then in your controller:

$scope.myClickHandler = function(){
  //call $http here
}
Community
  • 1
  • 1
pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
1

Now I resolved my issue... It needs apply on scope

like this:

$.ajax({
    url: Escudo.UrlHelper.baseUrl + 'Widgets/Notifications/GetLastNotifications',
    data: {
        notificationCount: 30
    },
    success: function (e) {
        $scope.$apply(function () {
            $scope.notifications = e.Messages;
        });
    }
});
David Slavík
  • 1,132
  • 1
  • 14
  • 23
  • 3
    While the $scope.$apply() will work, is there any reason why you wouldn't want to just use the built-in $http service? No $apply is necessary when going through that. – dnc253 Dec 11 '12 at 17:02