angularjs - Angular 组件通过 http 两种方式绑定(bind)到对象

标签 angularjs http components

我有一个名为“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.dataitemundefined。稍后当 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/

相关文章:

javascript - 使用 OpenLayers 3 作为 react 组件

javascript - ng Repeat 内部的编辑功能

http - 对于健康检查失败,我应该使用哪个 HTTP 状态代码?

javascript - 类似单选按钮行为的 Vue.js 组件

html - 如何自动下载可通过 html 表单获取的数据?我应该学什么?

c# - 为 System.Net.HttpClient get 构建查询字符串

.net - 语法高亮 : rich text box control for . NET

javascript - 使用 AngularJS 从 JSON 响应 ($http) 获取对象并将其作为 ng-click 上的变量传递

javascript - AngularJS 动态输入值绑定(bind)到数组模型

javascript - 指令加载时间非常长,检查加载时间的方法