code

약속이 해결되기 전에 지침이 렌더링되고 있습니다.

starcafe 2023. 2. 27. 23:25
반응형

약속이 해결되기 전에 지침이 렌더링되고 있습니다.

약속이 해결된 후에만 내용을 렌더링하도록 지시하는 데 문제가 있습니다.내 생각에는 말이지…then()원래 이렇게 해야 되는데 잘 안 되는 것 같아요.

컨트롤러는 다음과 같습니다.

// Generated by CoffeeScript 1.6.3
(function() {
  var sprangularControllers;

  sprangularControllers = angular.module('sprangularControllers', ['sprangularServices', 'ngRoute']);

  sprangularControllers.controller('productsController', [
    '$scope', '$route', '$routeParams', 'Product', 'Taxonomy', function($scope, $route, $routeParams, Product, Taxonomy) {
      Taxonomy.taxonomies_with_meta().$promise.then(function(response) {
        return $scope.taxonomies = response.taxonomies;
      });
      return Product.find($routeParams.id).$promise.then(function(response) {
        return $scope.currentProduct = response;
      });
    }
  ]);

}).call(this);

나의 지시:

// Generated by CoffeeScript 1.6.3
(function() {
  var sprangularDirectives;

  sprangularDirectives = angular.module('sprangularDirectives', []);

  sprangularDirectives.directive('productDirective', function() {
    return {
      scope: {
        product: '='
      },
      templateUrl: 'partials/product/_product.html',
      link: function(scope, el, attrs) {
        console.log(scope);
        console.log(scope.product);
        return el.text(scope.product.name);
      }
    };
  });

}).call(this);

스코프가 OK를 반환하고 개발 도구에서 체크인을 하면scope.product정의되지 않은 것은 아니지만 확인했을 때 약속이 해결되었기 때문이라고 추측하고 있습니다.

console.log(scope.product)그러나 정의되지 않은 반환..

문제에 관한 공식 스레드('지시가 대기하기 때문에 수정되지 않음'으로 신속하게 종료됨)에 기술된 바와 같이, 회피책은 지시사항을 다음과 같이 정리하는 것입니다.ng-if:

<div ng-if="myPromiseParam">
  <my-directive param="myPromiseParam">
</div>

값이 비동기적으로 입력되기 때문에 바인딩된 요소를 업데이트하는 워치 함수를 추가해야 합니다.

  link: function(scope, el, attrs) {
    scope.$watch('product', function(newVal) {
        if(newVal) { el.text(scope.product.name);}
    }, true);
  }

또한 많은 복잡성을 디렉티브컨트롤러로 이동하여 링크 함수를 사용하여 DOM을 조작할 수도 있습니다.

true세 번째 파라미터$watch이 디렉티브를 모델에 바인드하고 있기 때문에, 깊은 감시가 발생합니다.

다음은 좋은 예시를 포함한 몇 가지 링크입니다.
http://www.ng-newsletter.com/posts/directives.html
http://seanhess.github.io/2013/10/14/angularjs-directive-design.html

오래된 질문인 것은 알지만, 최신 답변을 시도해 보려고 합니다.

라우터를 사용하는 경우 ui-router와 ngRouter는 모두 URL 변경에 따른 약속을 해결하는 해결 메서드를 가지고 있습니다.이것에 의해, 그 루트로 전환해, 페이지의 내용을 렌더링 할 수 있습니다.

ngRouter Resolve 튜토리얼
ui-router 문서 해결

를 사용하는 대신 다른 옵션을 사용할 수 있습니다.$watch각도 약속 라이브러리를 사용하는 것입니다.구체적으로는$q.when()방법.여기에는 약속과 가치가 필요합니다.만약 그것이 약속이라면 그것은 발사될 것이다..then()그 약속이 해결되면.값이 있으면 약속으로 감싸서 즉시 해결합니다.

link: function(scope, el, attrs){
    $q.when(scope.product).then(function(product){
        scope.product = product;
        el.text(scope.product.name);
    });
}

또는 html만으로 아무것도 표시할 수 없는 몇 가지 방법이 있습니다.

<product-directive product='object'>
    <!-- Will hide span until product.name exists -->
    <span ng-show='product.name'>{{ product.name }}</span> 

    <!-- Will show default text until key exists -->
    {{ product.name || 'Nothing to see here' }}

    <!-- Will show nothing until key exists -->
    <span ng-bind='product.name'></span>
</product-directive>    

지시문에서 변수 $watch를 사용하여 변수의 업데이트된 값을 가져옵니다.

$q를 사용하여 약속을 해결할 수도 있습니다.

언급URL : https://stackoverflow.com/questions/21177582/directive-is-being-rendered-before-promise-is-resolved

반응형