2017-02-26 9 views
1

私はパラメータからデータを与えるコンポーネントを持っているシンプルなAPPを持っています。角1.5動的にコンポーネントを追加する

は、私は現在、私はこれ持って、ユーザーがクリックしたときにボタンの上に、このコンポーネントを複数回追加する:

<div ng-app="myApp" ng-controller="myCtrl"> 

    <my-component></my-component> 
    <br /> 
    <input type="button" ng-click="addComponent()" value="Add New Component"> 

    <div ng-repeat="c in components"> 
    {{c.content}} 
    </div> 
</div> 

と私の.jsを

angular.module("myApp", []).controller("myCtrl", function ($scope,$compile) { 
    $scope.components = []; 

    $scope.addComponent = function(){ 
     $scope.components.push({content: $compile('<my-component></my-component>')}); 
    } 

}); 

function componentCtrl($scope) { 
    this.text = "Hey I'm a component"; 

} 

angular.module("myApp").component('myComponent', { 
    template: '<span>{{$ctrl.text}}</span>', 
    controller: componentCtrl 
}); 

私はとして$なしの両方試してみましたコンパイルしますが、ページがロードされた後もコンポーネントを作成できません。最初のコンポーネントは正常にロードされます。 plunker「ねえ、私はコンポーネントです」が表示され、代わりに私は何か文字通り

<my-component></my-component> 

のいずれかを取得していない:https://plnkr.co/edit/IQe8ln?p=preview

答えて

3
私は何を期待

は、ボタンをクリックするとテキストで新しいコンポーネントがあることです

あなたは考え過ぎています。ただ、myComponentngRepeatを置く:

<my-component ng-repeat="c in components" text="c.text"></my-component> 

そしておそらくJSでこのような何か:

angular.module("myApp", []) 
.controller("myCtrl", function ($scope,$compile) { 
    $scope.components = []; 

    $scope.addComponent = function(text) { 
     $scope.components.push({text: text}); 
    } 
}); 

function componentCtrl($scope) { 
    // something here 
} 

angular.module("myApp").component('myComponent', { 
    template: '<span>{{$ctrl.text}}</span>', 
    controller: componentCtrl, 
    bindings: { 
    text: '=' 
    } 
}); 
+0

あなたは正しいです、時々私は、角度を深くしました。ありがとう! –

関連する問題