javascript - 组件中的 Angular JS 数据绑定(bind)不起作用

标签 javascript angularjs

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

问题是数据绑定(bind)不起作用,因为输入组件中的任何修改都不会考虑到 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;
  }

})();

最佳答案

我设法通过两种方式绑定(bind)来解决我的问题,并将表单元素放入对象中,而不是将其直接放入 View 中($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>'

关于javascript - 组件中的 Angular JS 数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946558/

相关文章:

javascript - 在 Bootstrap 模式中显示 sumoselect

php - CodeIgniter 和 Javascript/Jquery 库

javascript - js .off() 不适用于 <tr> 元素

javascript - 数据表过滤 href 值 - 绕过 anchor 过滤器

jquery - Angularjs - 在 for 循环中组合来自多个 $http 调用的数据

javascript - 当 $scope 被销毁时删除事件监听器

javascript - AngularJS 用 <select> 中的对象填充 $scope.selected

javascript - 选项 beginAtZero 在 angular-chart.js 中不起作用

javascript - 使用angular js检查井字游戏中是否获胜者的逻辑

javascript - .change() 与 .on( "change", handler ) 在 jQuery 中