我创建了一个简单的组件:
(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}}
)已更新,但输入值保持不变。
另一方面,当用户修改输入值时,表达式会正确更改。
没有抛出任何错误,没有任何错误。它甚至不是单向绑定,而是不寻常的数据流阻塞......
答案 0 :(得分:0)
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>
答案 1 :(得分:0)
问题在于如何更新数组:
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;