2016-06-21 75 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