【问题标题】:Angular component two way binding to object with httpAngular 组件通过 http 以两种方式绑定到对象
【发布时间】:2017-04-27 07:38:17
【问题描述】:

我有一个名为“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}}

但这不起作用,似乎它不能作为双向绑定起作用,这是:当formData发生变化时,组件不会改变dataitem值。

【问题讨论】:

    标签: angularjs http components


    【解决方案1】:

    发生的情况是 formData 最初不可用,并且组件未定义为 dataitem 绑定。在控制器中,您分配$scope.dataitem = this.dataitem;,导致$scope.dataitem 成为undefined。后来当http请求解析并且formData成为一个对象(数组,无论如何)它不会更新$scope.dataitem,因为这些引用之间没有连接。另一方面,this.dataitem 会自动更新。

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

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

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

    【讨论】:

    • 我不明白你的意思,我尝试不使用控制器但仍然无法正常工作。当http结果出现时,我是绑定应该更新值的两种方式
    • 当然,this.dataitem 更新没有问题。所以使用dataitem绑定到控制器(this.dataitem),不要重新分配给$scope.dataitem,因为这不会更新。我在答案中添加了解释。
    • 好的,我明白了,this.dataitem 会自动更新,但 $scope.dataitem 不会...但是如何在我的 html 数据项中显示?我试过没有在我的 html 中创建 $scope 像 {{dataitem}} 但仍然无法工作
    • $scope.dataitem 和 this.dataitem 之间没有引用。初始分配$scope.dataitem = this.dataitem 以后不会自动重新分配。这就是为什么您需要使用this.dataitem,它始终是最新的。
    • 我尝试在控制器中使用手表观看此数据项。 $scope.$watch('dataitem', function () { console.log(this.dataitem) }, true);但是不起作用,你知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2017-12-29
    相关资源
    最近更新 更多