Programing

격리 범위가있는 지시문의 템플릿에서 $ rootScope에 액세스 할 수없는 이유는 무엇입니까?

crosscheck 2020. 10. 9. 08:49
반응형

격리 범위가있는 지시문의 템플릿에서 $ rootScope에 액세스 할 수없는 이유는 무엇입니까?


격리 범위를 사용하면 지시문의 템플릿이 제어기 ( 'Ctrl') $ rootScope 변수에 액세스 할 수없는 것처럼 보이지만 지시문의 제어기에 나타납니다. 컨트롤러 ( 'Ctrl') $ scope 변수가 격리 범위에 표시되지 않는 이유를 이해합니다.

HTML :

<div ng-app="app">
    <div ng-controller="Ctrl">
        <my-template></my-template>
    </div>

    <script type="text/ng-template" id="my-template.html">
        <label ng-click="test(blah)">Click</label>
    </script>
</div>

자바 스크립트 :

angular.module('app', [])
    .controller('Ctrl', function Ctrl1($scope,  $rootScope) {
        $rootScope.blah = 'Hello';
        $scope.yah = 'World'
    })
    .directive('myTemplate', function() {
        return {
            restrict: 'E',
            templateUrl: 'my-template.html',
            scope: {},
            controller: ["$scope", "$rootScope", function($scope, $rootScope) {
                console.log($rootScope.blah);
                console.log($scope.yah);,

                $scope.test = function(arg) {
                    console.log(arg);
                }
            }]
        };
    });

JSFiddle

변수는 격리 범위없이 액세스됩니다. 격리 범위 행에 주석을 달면 알 수 있습니다.

        // scope: {},

이 방법을 사용하여 시도 할 수 있습니다. $root.blah

작업 코드

HTML

 <label ng-click="test($root.blah)">Click</label>

자바 스크립트

  angular.module('app', [])
    .controller('Ctrl', function Ctrl1($scope,  $rootScope) {
        $rootScope.blah = 'Hello';
        $scope.yah = 'World'
    })
    .directive('myTemplate', function() {
        return {
            restrict: 'E',
            templateUrl: 'my-template.html',
            scope: {},
            controller: ["$scope", "$rootScope", function($scope, $rootScope) {
                console.log($rootScope.blah);
                console.log($scope.yah);

                $scope.test = function(arg) {
                    console.log(arg);
                }
            }]
        };
    });

일반적으로 $rootScope컨트롤러와 지시문간에 공유해야하는 값을 저장 하는 사용하지 않아야 합니다. JS에서 전역을 사용하는 것과 같습니다. 대신 서비스를 사용하십시오.

상수 (또는 값 ... 사용이 유사 함) :

.constant('blah', 'blah')

https://docs.angularjs.org/api/ng/type/angular.Module

A factory (or service or provider):

.factory('BlahFactory', function() {
    var blah = {
        value: 'blah'
    };

    blah.setValue = function(val) {
      this.value = val;
    };

    blah.getValue = function() {
        return this.value;
    };

    return blah;
})

Here is a fork of your Fiddle demonstrating how you might use either


1) Because of the isolate scope $scope in your controller Ctrl and in the directive controller don't refer to the same scope - let's says we have scope1 in Ctrl and scope2 in directive.

2) Because of the isolate scope scope2 do not prototypicallly inherit from $rootScope ; so if you define $rootScope.blah there is no chance you can see it in scope2.

3) What you can access in your directive template is scope2

If I sum it up, here is the inheritance schema

    _______|______
    |            |
    V            V
$rootScope     scope2
    |
    V
  scope1


$rootScope.blah
> "Hello"
scope1.blah
> "Hello"
scope2.blah
> undefined

I know this an old question. But it didn't satisfy my inquisition about why the isolated scope won't be able to access properties in the $rootscope.

So I dug in the angular lib and found -

$new: function(isolate) {
  var ChildScope,
      child;

  if (isolate) {
    child = new Scope();
    child.$root = this.$root;
    child.$$asyncQueue = this.$$asyncQueue;
    child.$$postDigestQueue = this.$$postDigestQueue;
  } else {

    if (!this.$$childScopeClass) {
      this.$$childScopeClass = function() {
        // blah blah...
      };
      this.$$childScopeClass.prototype = this;
    }
    child = new this.$$childScopeClass();
  }

This is the function called by angular whenever a new scope is created. Here it's clear that any isolated scope is not prototypically inheriting the rootscope. rather only the rootscope is added as a property '$root' in the new scope. So we can only access the properties of rootscope from the $root property in the new isolated scope.

참고URL : https://stackoverflow.com/questions/23595866/why-cant-the-rootscope-be-accessed-in-the-template-of-a-directive-with-isolate

반응형