prosource

Angularjs - 다이렉트링크 함수의 $rootScope

probook 2023. 4. 3. 21:35
반응형

Angularjs - 다이렉트링크 함수의 $rootScope

rootscope를 디렉티브에 전달되는 의존관계로 어떻게 생각해야 할지 잘 모르기 때문에 이 질문을 합니다.

$rootScope에서 정보를 표시해야 하는 지침이 있습니다.

$rootScope를 디렉티브에 전달해야 한다고 생각했지만 이렇게 디렉티브를 작성하면 효과가 있는 것 같습니다.

.directive("myBar", function () {
 return {
    restrict: "E",
    transclude: true,
    replace: true,
    template:   '<div>' + 
                '<span ng-transclude></span>' + 
                '{{rsLabels.welcome}} {{rsUser.firstName}}!' + 
                '</div>'
}
})

이거 언제 해야 돼요?

.directive("myBar", function ($rootScope) {
 return {
    restrict: "E",
    transclude: true,
    replace: true,
    template:   '<div>' + 
                '<span ng-transclude></span>' + 
                '{{rsLabels.welcome}} {{rsUser.firstName}}!' + 
                '</div>'
}
})

명령어 링크 함수에 rootScope가 필요한 경우 rootScope를 사용할 수 있습니까?아니면 명령어 컨트롤러에서 사용할 필요가 있습니까?

.directive("myBar", function ($rootScope) {
 return {
    restrict: "E",
    transclude: true,
    replace: true,
    link: function (scope, element, attrs, rootScope) {
        rootScope.rsUser = { firstName: 'Joe' };
        rootScope.rsUser = { welcome: 'Welcome' };
    },
    template:   '<div>' + 
                '<span ng-transclude></span>' + 
                '{{rsLabels.welcome}} {{rsUser.firstName}}!' + 
                '</div>'
}
})

내 rootScope 데이터가 실행 함수로 정의됨

 .run(function ($rootScope) {

  $rootScope.rsLabels = { 
      welcome: 'Welcome'
  };

  $rootScope.rsUser = { 
     firstName: 'Joe'
  };
});

감사해요!

다음과 같이 할 수 있습니다.

{{$root.rsLabels.welcome}}

제 경험상 $scope는 모두 $rootScope에서 상속되기 때문에 표준 Javascript 프로토타입 상속 규칙에 따라 서비스로서 요청하지 않고 $scope의 데이터에 액세스할 수 있습니다.지시문의 범위 속성을 false 또는 {}(으)로 설정하면 더 이상 액세스할 수 없습니다.

.directive("myBar", function($rootScope) {
    return {
        restrict: "E",
        scope: { /* Isolate scope, no $rootScope access anymore */ },
        transclude: true,
        replace: true,
        template: '<div>' + 
                  '<span ng-transclude></span>' + 
                  '{{rsLabels.welcome}} {{rsUser.firstName}}!' + 
                  '</div>'
    };
});

예: http://jsbin.com/bequy/1/edit

각도 응용 프로그램에서 속성을 설정하고 가져오는 데 루트 스코프를 사용하지 않는 것이 좋습니다.$cacheFactory를 사용해 보십시오.그렇게 하면 다양한 요구에 대해 몇 가지 값을 캐시할 수도 있습니다.($cacheFactory 문서)

가끔 $scope를 사용해야 합니다.$root:

app.directive('setOrdinal', function() {
  return {
    link: function($scope, $element, $attr) {

      var steps = $scope.$root.steps;

      $scope.$watch(setOrdinal, function(value) {
        if (value)
        {
          // steps code here
        }
      });
    }
  };
});

app.controller('stepController', ['$scope', '$rootScope', 'GetSteps', function ($scope, $rootScope, GetSteps) {
  var s = $scope;
  var r = $rootScope;

  s.initialize = function(id)
  {
    GetSteps.get({id: id}, function(resp){
      r.steps = resp.steps;
    });
  };
}]);

이 같은 문제를 오랫동안 고민해 온 결과, 첫 번째 투고에서 간과되고 있는 점에 주목할 가치가 있다고 생각했습니다.내 원래 코드는 다음과 같습니다.

app.directive('countrymap', function() 
{
    return {
        link: function(scope, element, attrs) {
            scope.$watch("countryMap", function (newCountry, oldCountry) 
            {
                setTimeout( function() 
                {
                    //function body here    
                }, 100);
            })
        }
    };  
}]);

$rootScope를 사용해야 하는지 여부에 대한 보다 철학적인 디자인 질문 외에, 위의 제 코드에 대해 Mike의 솔루션에서 빠진 것 같은 명백한 잘못된 점이 하나 있습니다. $rootScope에 대한 참조입니다.저와 마찬가지로 지시 파일과 컨트롤러 파일을 분리한 경우 다음과 같이 코드를 수정해야 합니다.

app.directive('countrymap', ['$rootScope', function($rootScope) 
{
    return {
        link: function(scope, element, attrs) {
            $rootScope.$watch("countryMap", function (newCountry, oldCountry) 
            {
                setTimeout( function() 
                { 
                    //function body here
                }, 100);
            })
        }
    };  
}]);

단, 또 하나 궁금한 점이 있습니다.지침에서 $rootScope를 참조하지 않고 동일한 목표를 달성할 수 있습니까?물론 할 수 있죠.$rootScope 속성에 대한 변경을 브로드캐스트하여 모든 하위 범위에 변경 내용을 알리고 지시문의 변경 내용을 감시해야 합니다.

컨트롤러:

$rootScope.countryMap = 'thiscountry_map';
$rootScope.$broadcast( "countryMapChanged", $rootScope.countryMap );

지시:

app.directive('countrymapalt', [function() 
{
    return {
        link: function(scope, element, attrs) {
            scope.$on("countryMapChanged", function(event, map) 
            {
                setTimeout( function() 
                { 
                    //function body here
                }, 100);
            })
        }
    };  
}]);

또 다른 방법은 서비스를 만들고 해당 서비스에 $rootScope 및 기타 함수에 액세스하는 것입니다.★★★★★★★★★★...

app.service('myService', function ($rootScope) 
{
    this.removeItem = function (el) 
    {
       console.log('rootScope: ',$rootScope);
       return true;
    }
});


app.directive('draggable', function($document,myService) 
{
   return function(scope, element, attr) 
   {
        myService.removeItem({id:1})
   }
});

가능하다면 가장 좋은 방법은 Mike 솔루션입니다.그렇지 않다면, 내 해결책을 시도해봐.

언급URL : https://stackoverflow.com/questions/21736824/angularjs-rootscope-in-directive-link-function

반응형