【问题标题】:Angular JS data binding in component is not working组件中的 Angular JS 数据绑定不起作用
【发布时间】:2016-10-23 03:04:14
【问题描述】:

我正在使用 Angular JS 1.5.6 组件来动态构建表单。层次结构如下: index.html 调用组件 my-view 调用组件 my-form 调用单一组件,如输入和按钮。

问题是数据绑定不起作用,因为输入组件中的任何修改都没有考虑到 my-view 组件中。

除了我有一个奇怪的行为,每次我更新输入值时,都会调用查看组件函数。

我有plunkered这个,提交按钮触发console.log(所以需要打开firebug才能看到它的作用)。

这是我的 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;
  }

})();

【问题讨论】:

    标签: javascript angularjs


    【解决方案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>'
    

    【讨论】:

      猜你喜欢
      • 2015-06-24
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2017-06-24
      • 1970-01-01
      相关资源
      最近更新 更多