Call AngularJS function on document ready

后端 未结 2 1196
无人及你
无人及你 2020-12-23 14:40

Is there a way to call an Angular function from a JavaScript function?

function AngularCtrl($scope) {
  $scope.setUserName = function(student){  
    $scope.         


        
相关标签:
2条回答
  • 2020-12-23 15:03

    Angular has its own function to test on document ready. You could do a manual bootstrap and then set the username:

    angular.element(document).ready(function () {
        var $injector = angular.bootstrap(document, ['myApp']);
        var $controller = $injector.get('$controller');
        var AngularCtrl = $controller('AngularCtrl');
        AngularCtrl.setUserName();
    });
    

    For this to work you need to remove the ng-app directive from the html.

    0 讨论(0)
  • 2020-12-23 15:07

    The answer above although correct, is an anti-pattern. In most cases when you want to modify the DOM or wait for the DOM to load and then do stuff (document ready) you don't do it in the controller but in he link function.

    angular.module('myModule').directive('someDirective', function() {
      return {
        restrict: 'E',
        scope: {
          something: '='
        },
        templateUrl: 'stuff.html',
        controller:  function($scope, MyService, OtherStuff) {
            // stuff to be done before the DOM loads as in data computation, model initialisation...
        },
        link: function (scope, element, attributes) 
            // stuff that needs to be done when the DOM loads
            // the parameter element of the link function is the directive's jqlite wraped element
            // you can do stuff like element.addClass('myClass');
            // WARNING: link function arguments are not dependency injections, they are just arguments and thus need to be given in a specific order: first scope, then element etc.
        }
      };
    });
    

    In all honesty, valid use of $document or angular.element is extremely rare (unable to use a directive instead of just a controller) and in most cases you're better of reviewing your design.

    PS: I know this question is old but still had to point out some best practices. :)

    0 讨论(0)
提交回复
热议问题