sourcecode

Angularjs에서 $compile을 지시 외에 사용하려면 어떻게 해야 합니까?

codebag 2023. 10. 10. 20:16
반응형

Angularjs에서 $compile을 지시 외에 사용하려면 어떻게 해야 합니까?

사용하고싶습니다$compile명령이 아닌 함수 내부의 컨트롤러에 저장됩니다.가능합니까?저는 아래 코드를 시도하고 있습니다.

$compile('<div ng-attr-tooltip="test">Cancel</div>')(scope)

그러나 이는 범위를 던지는 것은 정의되지 않은 오류입니다.지나가려고 했습니다.$scope기능 내부에 있지만 작동하지 않습니다.

당신이 DOM을 바꿨다는 걸 앵귤러가 어떻게 알겠습니까?($compile service 사용) 추가 전에 html을 컴파일해야 합니다.

지시를 벗어나 접근해야 하는 경우 인젝터를 생성할 수 있습니다.

$(function() {
  // myApp for test directive to work, ng for $compile
  var $injector = angular.injector(['ng', 'myApp']);
  $injector.invoke(function($rootScope, $compile) {
    $('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope));
  });
});

주의할 점은 이전 답변에서 인젝터(var $injector = angular.injector(['ng', 'myApp']);)은 현재 실행 중인 각 앱에 컴파일 지시문을 추가하지 않으며 대신 새 프로그램을 만듭니다.

앱에 새로운 지시어를 동적으로 추가하려면 이미 존재하는 주입기를 사용해야 합니다.

$(function() {
  angular.element(document).injector().invoke(function($rootScope, $compile) {
    $('body').prepend($compile('<div ng-attr-tooltip="test">Cancel</div>')($rootScope));
  });
});

문서의 마지막 단락을 참조하십시오.

나는 @바이브하브 자인의 대답을 시도했지만 성공하지 못했습니다.조금 더 파헤쳐 본 결과 Angular 1.3과 jQuery:

$(function() {
  angular.element(document).injector().invoke(['$compile', function ($compile) {
    // Create a scope.
    var $scope = angular.element(document.body).scope();
    // Specify what it is we'll be compiling.
    var to_compile = '<div ng-attr-tooltip="test">Cancel</div>';
    // Compile the tag, retrieving the compiled output.
    var $compiled = $compile(to_compile)($scope);
    // Ensure the scope and been signalled to digest our data.
    $scope.$digest();
    // Append the compiled output to the page.
    $compiled.appendTo(document.body);
  });
});

나는 이 일을 했다.

var SCOPE;
app_module.controller('appController', function ($scope, $compile) {
    SCOPE = $scope;
    $scope.compile = function (elem_from, elem_to) {
        var content = $compile(angular.element(elem_from))($scope);
        angular.element(elem_to).append(content);
    }
});

이런식으로

SCOPE.compile(elem1.content, elem2);

페이지의 변경사항을 적용하기 위해 html을 다시 컴파일해야 할 때 다음과 같은 방법으로 html을 다시 컴파일했습니다.

다른 링크로 이동했다가 페이지로 다시 돌아가려고 했는데 어떤 이유에서인지 각도 코드가 컴파일되지 않을 때 발생합니다.

그래서 로드 이벤트 때 페이지의 html 부분을 다시 컴파일하여 수정하였습니다.

function OnLoad() {
angular.element("form:first").injector().invoke(['$compile', function ($compile) {
    var $scope = angular.element("form:first").scope();
    $compile("form:first")($scope);
}]);
}

아래는 앱 선언문입니다.

<form ng-app="formioApp" ng-controller="formioAppCtrl">

그리고 OnLoad() 함수는 해당 페이지의 html 요소의 onload 이벤트에 할당됩니다.

언급URL : https://stackoverflow.com/questions/22370390/how-can-we-use-compile-outside-a-directive-in-angularjs

반응형