2015-12-14 7 views
9

私はv1.5コンポーネントを使用しています。これは基本的に(わかっている限り)ベストプラクティスのためのラッパーです。コンポーネントの1.5リリースに関するAngularjsのv1.5コンポーネント内の属性にアクセスする方法は?

詳細情報はここで見つけることができます:http://toddmotto.com/exploring-the-angular-1-5-component-method/

私は、次のしている:

<span>Correclty showing: {{ data.type }}</span> 
<book class="details" type="data.type"></book> 

そして、それはコンポーネントの定義です:

angular 
.module('app') 
.component('book', { 
    bindings: { 
     type: '=' 
    }, 
    template: function($element, $attrs) { 
     // Have tried A): 
     // console.log($attrs.type); // <- undefined 

     // And B): 
     $attrs.$observe('type', function(value) { 
      console.log(value); // <- undefined 
     }); 

     // But.. C): 
     return "This works though {{ book.type }}"; // <- renders 
    } 
}); 

両方A)B)変動はundefinedを返します。 C)が正しくレンダリングされます。

テンプレート文字列を返す前に、テンプレート関数内の属性にアクセスする方法はありますか?

答えて

13

1.5で、templateUrlは今すぐドキュメント:https://docs.angularjs.org/guide/componentに従って注射薬を服用します。 ng-srict-diを使用した場合、注射液を指定しない限りエラーが発生します。私はng-annotateを使用して頭痛を救い、コードをきれいに保ちます。ここでは例としては、(活字体で)です:

バニラJSで
import IRootElementService = angular.IRootElementService; 
    import IAttributes = angular.IAttributes; 

    angular.module('app').component('book', { 

     /*@ngInject*/ 
     templateUrl($element:IRootElementService, $attrs:IAttributes) { 
      // access to the $element or $attrs injectables 
     } 

    }); 

またはNG-注釈なし:

angular.module('app').component('book', {  
     templateUrl: ['$element', '$attrs', function($element, $attrs) { 
      // access to the $element or $attrs injectables 
     }], 
    }); 
+0

私はNG-厳密ジ、NG-注釈を見て、その後、非常に興味深いですよ@ ng注入? attrがどのように注射可能であるかを明確にすることはできますか?他の依存関係に基づいてtemplateUrlを作成する方法を提案する回答を探しています。 – iJames

+0

これはAngular 1.5のドキュメントで、コンポーネントアーキテクチャでは$ elementと$ attrsが注入可能です。詳細については、答えにリンクされているコンポーネントガイドを参照してください。 – Jeff

+1

@Jeff $要素サービスを注入する必要がありますか?私はそれを注入せずに試したが、とにかく動作するようだ。 – user449689

関連する問題