programing

콜 앵귤러문서 준비 완료 시 JS 함수

cafebook 2023. 3. 19. 18:29
반응형

콜 앵귤러문서 준비 완료 시 JS 함수

JavaScript 함수에서 Angular 함수를 호출하는 방법이 있습니까?

function AngularCtrl($scope) {
  $scope.setUserName = function(student){  
    $scope.user_name = 'John';
  }
}

HTML에 다음 기능이 필요합니다.

jQuery(document).ready(function(){
  AngularCtrl.setUserName();
}

여기서의 문제는 페이지가 로드될 때 내 HTML 코드가 존재하기 때문에 html의 ng 디렉티브가 컴파일되지 않는다는 것입니다.그래서 저는$compile(jQuery("PopupID"));DOM이 로드되었을 때.

문서의 Angular 함수를 호출할 수 있는 방법이 있습니까?

Angular에는 문서 준비 상태에서 테스트하는 자체 기능이 있습니다.수동 부트스트랩을 실행하여 사용자 이름을 설정할 수 있습니다.

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

이 작업을 수행하려면 html에서 ng-app 지시문을 삭제해야 합니다.

위의 답변은 맞지만 안티패턴입니다.대부분의 경우 DOM을 수정하거나 DOM이 로드될 때까지 기다렸다가 (문서 준비 완료) 작업을 컨트롤러에서 하는 것이 아니라 링크 기능에서 수행합니다.

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.
    }
  };
});

솔직히 말해서 $document 또는 angular.element를 유효하게 사용하는 경우는 극히 드물기 때문에(컨트롤러뿐만 아니라 디렉티브를 사용하는 것은 불가능), 대부분의 경우 설계를 재검토하는 것이 좋습니다.

PS: 이 질문은 오래되었지만 몇 가지 베스트 프랙티스를 지적해야 합니다.:)

언급URL : https://stackoverflow.com/questions/13838205/call-angularjs-function-on-document-ready

반응형