【问题标题】:An input inside a component breaks two-way binding of AngularJS组件内的输入破坏了 AngularJS 的双向绑定
【发布时间】:2017-09-06 22:17:45
【问题描述】:

我创建了一个简单的组件:

(function (module) {
    'use strict';
    function SomeCtrl() {
        this.foo = function (event) {
            this.someArray.forEach(function (part, index, array) {
                //somelogic
                array[index] = array[index] + " (foo)";
            });            
        }
    }

    module.component('componentName', {
        templateUrl: 'blah.html',
        controller: SomeCtrl,
        bindings: {
            someArray: '=',
        }
    });
})(module);

HTML模板也很简单:

<div class="input-group">
    <input type="text" class="form-control" ng-model="$ctrl.someArray" />
    <span class="input-group-btn">
        <a class="btn btn-default" ng-click="$ctrl.foo($event)">
            <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
        </a>
    </span>
</div>
{{$ctrl.someArray}}

基本上它是一些输入和按钮。输入与数组绑定,并在按钮单击时修改数组。

不幸的是,组件的行为很奇怪。表达式 ({{$ctrl.someArray}}) 已更新,但输入值保持不变。

另一方面,当用户修改输入值时,表达式会正确改变。

没有抛出任何错误,什么也没有。它甚至不是单向绑定,而是不寻常的数据流块......

【问题讨论】:

  • 你能创建一个 plunker/fiddle 吗?

标签: javascript angularjs data-binding binding


【解决方案1】:

var module = angular.module('myApp',[]);
    module.component('componentName', {
    controller: function SomeCtrl() { 
        this.foo = function (event, array) { 
 this.someArray.forEach(function (part, index, array) {
                //somelogic
              //  array[index] ={'no':array[index].no+ " foo"};
                 console.log(array[index] ={'no':array[index].no+ " foo"});
            });  
          
        }
    }, 
        template: `<div class="input-group">
    <input type="text" ng-repeat="some in $ctrl.someArray" class="form-control" ng-model="some.no" /><br>{{$ctrl.someArray}}
   
        <button class="btn btn-default" ng-click="$ctrl.foo($event, $ctrl.someArray)">
        Okay
        </button>
 
</div>`,         
        bindings: {
            someArray: '=',
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
<body ng-app="myApp">
<div ng-init="arrays=[{'no':'1'},{'no':'2'},{'no':'3'},{'no':'4'},{'no':'5'}]">
<component-name some-array="arrays"></component-name>
</div>
</body>

【讨论】:

    【解决方案2】:

    问题在于数组是如何更新的:

    this.someArray.forEach(function (part, index, array) {
        //somelogic
        array[index] = array[index] + " (foo)";
    }); 
    

    AngularJS 似乎没有检测到对数组执行的这种更改。解决方法很简单:

    var newArray = []
    this.someArray.forEach(function (part, index, array) {
        //somelogic
        newArray.push(array[index] + " (foo)");
    }); 
    this.someArray = newArray;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多