Question

Something weird is going on in my AngularJS application. I have a view which has a list of anchor tags bound to an array of objects (I'm using ng-repeat to render the list). Each one of the anchor tag has an ng-click bound to a method on the controller. The method is as follows:

    $scope.onSiteSelected = function ($event, site) {
        $event.preventDefault();
        $.ajax({
            url: '/Site/GetSiteMap/' + site.Id,
            success: function (response) {
                if (response && response.length > 0) {
                    menuManager.setSiteMap($scope.$root.menu, response[0]);
                    var url = response[0].Children[0].Settings.Url;
                    $location.path(url);
                }
            }
        });
    }   

The url var is being initialized to the correct value every time. But, when I click on the anchor tag the first time, $location.path(url) does nothing, and when I click it for a second time, it does navigate to the target url.

UPDATE:

Ok I got it working by using the $http service as follows:

    $scope.onSiteSelected = function ($event, site) {
        $event.preventDefault();
        var address = '/Site/GetSiteMap/' + site.Id;
        $http.get(address)
            .success(function (response) {
                if (response && response.length > 0) {
                    menuManager.setSiteMap($scope.$root.menu, response[0]);
                    var url = response[0].Children[2].Settings.Url;
                    $location.path(url);
                }
            });
    }

Does it really make a difference if I used $,ajax or $http? I thought the two can be used interchangeably...?

Was it helpful?

Solution

No you cannot use them interchangibly, $.ajax is jQuery whereas $http is angular's http service.

Resist the urge to use jQuery as there is almost always a way to do it in the angular way.

That being said, if you do something outside of angular world, (mostly callbacks didn't occur from angular), you need to apply the changes to force a digest cycle.

$.doSth(function callback() {
    $scope.$apply(function () {
        // your actual code
    });
}); 

Please read the most voted answer in "Thinking in AngularJS" if I have a jQuery background? . This would guide you to avoid using jQuery where there is an alternative.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top