2017-05-27 6 views
0

私はangularjsの初心者なので、何か間違っているかもしれません。私がしようとしているのは、別のコンポーネントコントローラの変数をタグを介して別のコンポーネントに渡すことです。以下はサンプルコードです。Angularjs 1.6.4:コントローラー変数をコンポーネントタグに渡す

ポストview.template.htmlは、ビューを投稿する所属コンポーネント:

<ul class="list-group"> 
<li class="list-group-item"> 
    <h4 class="list-group-item-heading">{{model.post.title}}</h4> 
    <p class="list-group-item-text">{{model.post.description}}</p> 
</li> 
</ul> 

{{model.post.id}} <!-- getting value here --> 
<rating-creator rating-type="1" parent-id="model.post.id"></rating-creator> 

評価-creator.component.js:

(function() { 
    "use strict"; 

    var module = angular.module(__appName); 

    function controller() { 
     var model = this; 

     model.$onInit = function() { 
      //getting undefined here. Why? 
      console.log("parent:"+model.parentId); 
     }; 
    } 

    module.component("ratingCreator", { 
     templateUrl: "components/rating-creator/rating-creator.template.html", 
     bindings: { 
      ratingType: "<", 
      parentId: "<" 
     }, 
     controllerAs: "model", 
     controller: [controller] 
    }); 

    }()); 
+0

デバッグのために '$ scope'を注入してコンソールにログインしてください – cYrixmorten

+1

コントローラのプロパティ値は配列ではありません – charlietfl

+1

[$ onChangesライフサイクルフック](https://docs.angularjs。 org/api/ng/service/$ compile#life-cycle-hooks)を使用して、initの後に値が使用可能になるかどうかを確認します。 – georgeawg

答えて

1

問題はmodel.post.idが利用できない可能性が最も高いですコンポーネントがインスタンス化されているときmodel.post.idの値がundefined以外の場合にのみ、ng-ifを使用してコンポーネントのインスタンスを生成してみてください。それは次のようになります。

コントローラ

app.controller('MainCtrl', function($scope, $timeout) { 
    var model = this; 

    // simulating model.post.id not being available on page load 
    $timeout(function() { 
    model.post = { 
     id: 123 
    }; 
    }, 1000); 
}); 

HTMLここ

<rating-creator ng-if="model.post.id" rating-type="1" parent-id="model.post.id"></rating-creator>

機能を実証plunkerです。 $timeoutを使用して、model.post.idが非同期に設定されていることをシミュレートします。

うまくいけば助けてください!

関連する問題