document ready in AngularJS

12,172

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)">
Share:
12,172
user500468
Author by

user500468

Updated on June 08, 2022

Comments

  • user500468
    user500468 almost 2 years

    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>
    
  • user500468
    user500468 almost 10 years
    Im just a newbie when It comes to AngularJS, so I don't know how directives works. Do you have an solution for non pro developer?
  • Justin Niessner
    Justin Niessner almost 10 years
    @user500468 - The solution for a non-pro developer is to read the documentation, understand what is going on, and still do it the right way. I linked to the documentation so you can take a look and get started.
  • user500468
    user500468 almost 10 years
    Thank you. Im going to give it a shot.
  • Justin Niessner
    Justin Niessner almost 10 years
    @user500468 - I just updated my answer as your problem may be easily solved without using jQuery at all.