Programing

AngularJS-프로그래밍 방식으로 새 격리 된 범위를 어떻게 만들 수 있습니까?

lottogame 2020. 10. 8. 07:37
반응형

AngularJS-프로그래밍 방식으로 새 격리 된 범위를 어떻게 만들 수 있습니까?


Angular.factory로 AlertFactory를 만들고 싶습니다. 다음과 같은 HTML 템플릿을 정의했습니다.

var template = "<h1>{{title}}</h1>";

제목은 컨트롤러를 호출하여 제공되며 다음과 같이 적용됩니다.

var compiled = $compile(template)(scope);
body.append(compiled);

그렇다면 컨트롤러에서 공장으로 격리 된 범위를 어떻게 전달할 수 있습니까? 컨트롤러에서 코드를 사용하고 있습니다.

AlertFactory.open($scope);

그러나 $ scope는 전역 컨트롤러 범위 변수입니다. 제목 속성만으로 공장에 대한 작은 범위를 전달하고 싶습니다.

감사합니다.


새 범위를 수동으로 만들 수 있습니다.

새 스코프 $rootScope를 삽입하는 경우 또는 컨트롤러 스코프에서 생성 할 수 있습니다. 분리 된 상태로 만드는 것은 중요하지 않습니다.

var alertScope = $scope.$new(true);
alertScope.title = 'Hello';

AlertFactory.open(alertScope);

여기서 핵심은에 전달 true하는 것입니다 $new.이 매개 변수는에 대한 하나의 매개 변수를 허용 isolate하므로 상위에서 범위를 상속하지 않습니다.

자세한 내용은 http://docs.angularjs.org/api/ng.$rootScope.Scope#$new 에서 찾을 수 있습니다.


보간 만 필요한 경우 $ compile 대신 $ interpolate 서비스를 사용하면 범위가 필요하지 않습니다.

myApp.factory('myService', function($interpolate) {
    var template = "<h1>{{title}}</h1>";
    var interpolateFn = $interpolate(template);
    return {
        open: function(title) {
            var html = interpolateFn({ title: title });
            console.log(html);
            // append the html somewhere
        }
    }
});

테스트 컨트롤러 :

function MyCtrl($scope, myService) {
    myService.open('The Title');
}

깡깡이


다음은 단계입니다.

  1. 다음을 사용하여 HTML을 DOM에 추가합니다. var comiledHTML = angular.element(yourHTML);
  2. 원하는 경우 새 범위 만들기 var newScope = $rootScope.$new();
  3. $ comile (); 호출 링크 함수를 반환하는 함수var linkFun = $compile(comiledHTML);
  4. linkFun을 호출하여 새 범위 바인딩 var finalTemplate = linkFun(newScope);
  5. DOM에 finalTemplate 추가 YourHTMLElemet.append(finalTemplate);

내 plunkr를 확인하십시오. 렌더링 지시문을 사용하여 프로그래밍 방식으로 위젯 지시문을 생성하고 있습니다.

https://plnkr.co/edit/5T642U9AiPr6fJthbVpD?p=preview

angular
  .module('app', [])
  .controller('mainCtrl', $scope => $scope.x = 'test')
  .directive('widget', widget)
  .directive('render', render)

function widget() {
  return {
    template: '<div><input ng-model="stuff"/>I say {{stuff}}</div>'
  }
}

function render($compile) {
  return {
    template: '<button ng-click="add()">{{name}}</button><hr/>',
    link: linkFn
  }

  function linkFn(scope, elem, attr) {
    scope.name = 'Add Widget';
    scope.add = () => {
      const newScope = scope.$new(true);
      newScope.export = (data) => alert(data);
      const templ = '<div>' +
                      '<widget></widget>' +
                      '<button ng-click="export(this.stuff)">Export</button>' +
                    '</div>';
      const compiledTempl = $compile(templ)(newScope);
      elem.append(compiledTempl);
    }
  }
}

격리 범위에 대해 말할 때 지시문에 대해 이야기하고 있다고 가정합니다.

다음은이를 수행하는 방법의 예입니다. http://jsfiddle.net/rgaskill/PYhGb/

var app = angular.module('test',[]);

app.controller('TestCtrl', function ($scope) {
    $scope.val = 'World';
});

app.factory('AlertFactory', function () {

    return {
        doWork: function(scope) {
            scope.title = 'Fun';    
            //scope.title = scope.val;  //notice val doesn't exist in this scope
        }
    };

});

app.controller('DirCtrl', function ($scope, AlertFactory) {
    AlertFactory.doWork($scope);  
});

app.directive('titleVal',function () {
    return {
        template: '<h1>Hello {{title}}</h1>',
        restrict: 'E',
        controller: 'DirCtrl',
        scope: {
            title: '='
        },
        link: function() {

        }
    };

});

Basically, attach a controller to a directive that has defined an isolate scope. The scope injected into the directive controller will be an isolate scope. In the directive controller you can inject your AlertFactory with wich you can pass the isolate scope to.

참고URL : https://stackoverflow.com/questions/15559442/angularjs-how-can-i-create-a-new-isolated-scope-programmatically

반응형