Pattle
Pattle

Reputation: 6016

jQuery code not executing in Angularjs controller

I have the following Angularjs controller that loads a JSON file and adds it to the scope so I can use it in the view. I then have some jQuery code but this code is never getting executed. I thought by placing the code in $scope.$on('$viewContentLoaded', function() { it would wait for the page to load but I think that's not the case. Does anyone know where I'm going wrong?

myApp.controller('pageController', function($scope) {

$.getJSON("data.json", function(data) {
    $scope.data = data;
});

$scope.$on('$viewContentLoaded', function() {
    //This event never gets fired
    $(".more").hover(function(e) {
        alert('here');
    });
});

Upvotes: 0

Views: 155

Answers (1)

apairet
apairet

Reputation: 3172

The getJSON from jQuery happens outside the 'angular' world and needs to be wrapped in an scope.$apply

Try the following:

$.getJSON("data.json", function(data) {
    $scope.apply(function () {
        $scope.data = data;
        //This event never gets fired
        $(".more").hover(function(e) {
            alert('here');
        });
    });      

});

I would recommend to use $http or $resource service from angular. If you use them, you do not need the call $apply anymore

Upvotes: 1

Related Questions