我有一个名为“formData”的范围对象。
在我的页面中,用户选择一个数据源,然后使用 http 提供程序将结果存储到 formData。
$http.get($scope.options.dataSource.transport.read(id))
.success(function (data, status, headers, config) {
$scope.formData = data.value[0];
})
.error(function (data, status, header, config) {
});
然后在我的 html 中,我想使用另一个组件来传递我从 http 请求中检索到的 formData。
<input-text field="Code" caption="Code" dataitem="formData"></input-text>
在输入文本组件中我有
var inputText = {
templateUrl: 'Input-text.tml.html',
bindings: {
field: '@',
caption: '@',
dataitem: '='
},
controller: function ($scope) {
$scope.field = this.field;
$scope.caption = this.caption;
$scope.dataitem = this.dataitem;
}
}
inputText.$inject = ['$scope'];
并在 Input-text.tml.html 中
{{dataitem}}
但这不起作用,似乎它不能作为双向绑定(bind)工作,这是:当 formData 更改时,组件不会更改 dataitem
值。
最佳答案
发生的事情是 formData
最初不可用,并且组件未定义为 dataitem
绑定(bind)。在 Controller 中,您进行赋值 $scope.dataitem = this.dataitem;
,这导致 $scope.dataitem
为 undefined
。稍后当 http 请求解析并且 formData
成为对象(数组,无论什么)时,它不会更新 $scope.dataitem
因为这些引用之间没有连接。另一方面,this.dataitem
自动更新。
不要将 dataitem
重新分配给 scope 属性,您不需要它:
controller: function () {
// use this.dataitem directly
}
删除 $scope
并使用 dataitem
绑定(bind)到 Controller 。在模板中它将变为 {{ $ctrl.dataitem.whatever }}
。
关于angularjs - Angular 组件通过 http 两种方式绑定(bind)到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41100841/