2016-06-21 68 views
1

我正在使用Angular JS 1.5.6組件來動態構建表單。層次結構如下:index.html調用組件my-view,它調用組件my-form,它調用輸入和按鈕等單位組件。組件中的角度JS數據綁定不起作用

問題是數據綁定不起作用,因爲輸入組件中的任何修改都不會被考慮到my-view組件中。

此外,我有一個奇怪的行爲,每次我更新輸入值,調用查看組件功能。

我有plunkered這個,提交按鈕觸發console.log(所以需要打開螢火蟲才能看到它的行動)。

這裏是我的index.html

<body ng-app="MyApp"> 
    <my-view></my-view> 
</body> 

下面是myView.html

<div class="container"> 
    <h2>With component myform</h2> 
    <my-form form-elements=" 
    [{type:'input', label:'First name', placeholder:'Enter first name',model:$ctrl.userData.firstName, id:'firstName'}, 
    {type:'input', label:'Last name', placeholder:'Enter last name',model:$ctrl.userData.lastName, id:'lastName'}, 
    {type:'button', label:'Submit', click:$ctrl.click()}]"></my-form> 
</div> 

<div class="container"> 
    <h2>Check data binding</h2> 
    <label>{{$ctrl.userData.firstName}}</label> 
    <label>{{$ctrl.userData.lastName}}</label> 
</div> 

這裏是myView.js

(function() { 
    'use strict'; 

    angular.module('MyApp').component('myView', { 
    templateUrl: 'myView.html', 
    controller: MyViewController, 
    bindings: { 
     viewFormElements: '<' 
    } 
    }); 

    function MyViewController() { 
    this.userData = { 
     firstName: 'François', 
     lastName: 'Xavier' 
    }; 

    function click() { 
     console.log("Hello " + this.userData.firstName + " " + this.userData.lastName); 
    } 

    this.click = click; 
    } 

})(); 

回答

1

我設法解決我的問題與2路結合並通過將表單元素的對象,而不是把它直接在視圖($ ctrl.formElements )。它在plunker

myView.html

<div class="container"> 
    <h2>With component myform</h2> 
    <my-form form-elements=$ctrl.formElements></my-form> 
    </div> 
    <div class="container"> 
    <h2>Check data binding</h2> 
    <label>{{$ctrl.formElements}}</label><br /> 
</div>' 
0

form-elements語法看起來很雜亂,難於閱讀,並且在這種情況下似乎不起作用。使用這個來代替:

<input type="text" placeholder="Enter first name" ng-model="$ctrl.userData.firstName" id="firstName"> 
<br> 
<input type="text" placeholder="Enter last name" ng-model="$ctrl.userData.lastName" id="lastName"> 
<br> 
<input type="button" value="Submit" ng-click="$ctrl.click()"> 

Pluker:http://plnkr.co/edit/fnZEcS8WXnb48a2I3M2M?p=preview

+0

謝謝你的答案,但它並沒有回答這個問題。做你的建議會打破我的架構和我的等級。我有這樣的層次結構,因爲我的目標是在幾個不同的視圖中使用my-form組件。 – Mouss