GomuGomuNoRocket
GomuGomuNoRocket

Reputation: 829

Angular component two way binding to object with http

I have a scope object named 'formData'.

In my page, the user chooses a dataSource and with http provider I store the result to 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) {
 });

Then in my html I want to use another component passing the formData I retrieve from the http request.

<input-text field="Code" caption="Code" dataitem="formData"></input-text>

In input-text component i have

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'];

And in Input-text.tml.html

{{dataitem}}

But this doesn't work, seems it's not working as two way binding, this is: When formData changes, the component doesn't change the dataitem value.

Upvotes: 1

Views: 966

Answers (1)

dfsq
dfsq

Reputation: 193271

What happens is that formData is not available initially, and component gets undefined as dataitem binding. In controller you make assignment $scope.dataitem = this.dataitem; which results in $scope.dataitem being undefined. Later when http request resolves and formData becomes an object (array, whatever) it however is not going to update $scope.dataitem because there is not connection between those references. On the other hand, this.dataitem updates automatically.

Don't reassign dataitem to scope property, you don't need it:

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

Drop $scope and use dataitem bound to controller. In template it will become {{ $ctrl.dataitem.whatever }}.

Upvotes: 1

Related Questions