document ready in AngularJS

user500468 picture user500468 · Jul 17, 2014 · Viewed 12.1k times · Source

I want to fire some jQuery code when you click on a checkbox. The problem is that when I click on a selectbox first time when the page is loaded, nothing happens. But when I click again, the jQuery-code is executed. I've tried to set angular.element(ready) as below, but it dont work:

angular.element(document).ready(function() {
        $http.get($rootScope.appUrl + '/nao/test/test')
            .success(function(data, status, headers, config) {
                $scope.test = data.data;
        });
        $scope.testa = function() {
                $('.checkboxfisk').click(function() {
                var fish = $(this).attr('id');
                alert(fish);    
                });

        };
});

<tr ng-repeat="info in test"><td>{{info.stracka}}</td><td>{{info.tid}}</td><td><input type="checkbox" id="{{info.id}}" class="checkboxfisk" ng-click="testa()"></tr>

Answer

Justin Niessner picture Justin Niessner · Jul 17, 2014

The proper way to interact with the DOM in Angular is to create your own custom directive. You can then wire up the jQuery handler in the postLink function of you directive (which Angular runs when it builds the page on load). Your handler will be there and waiting when the page is ready.

Take a look at Angular's documentation for directives and give it a shot:

AnuglarJS: Developer Guide: Directives

Looking at your example, though, that may be too much. There's no need to have jQuery listen for the click event at all. You just need to remove the jQuery wrapper around your function definition and let Angular handle the click event itself:

$scope.testa = function(id) {
    alert(id);
};

And then modify your ng-click attribute to pass the id in the expression:

<input type="checkbox" 
       id="{{info.id}}" 
       class="checkboxfisk" 
       ng-click="testa(info.id)">