Angular组件使用http双向绑定到对象

时间:2016-12-12 12:21:30

标签: angularjs http components

我有一个名为'formData'的范围对象。

在我的页面中,用户选择一个dataSource,并使用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}}

但这不起作用,似乎它不是双向绑定,这是:当formData更改时,组件不会更改dataitem值。

1 个答案:

答案 0 :(得分:1)

最初,formData不可用,组件未定义为dataitem绑定。在控制器中,您可以进行作业$scope.dataitem = this.dataitem;,从而导致$scope.dataitemundefined。稍后当http请求解析并且formData成为对象(数组,无论如何)时,它不会更新$scope.dataitem,因为这些引用之间没有连接。另一方面,this.dataitem会自动更新。

不要将dataitem重新分配到范围属性,您不需要它:

controller: function () {
    // use this.dataitem directly
}

删除$scope并使用绑定到控制器的dataitem。在模板中,它将变为{{ $ctrl.dataitem.whatever }}

相关问题