Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS - Data binding in directive is not working

I have an issue with a data binding inside a directive, which call another directive.

Here is the main directive :

var app = angular.module('app');

app.directive("myMainDirective", function ($http) {
return {
    scope: {
        paramId: '='
    },
    link: function (scope) {
        $http.get('some/url/' + scope.paramId+ '.json'
        ).success(function (data) {
                scope.idFromServer = data;
            });
    },
    template: '<span other-directive id="idFromServer"></span>'
}
});

Here is the other directive :

var app = angular.module('app');

app.directive("otherDirective", ['$http', function(http) {
return {
    template: "<span>{{name}}</span>",
    scope: {
        id: "="
    },
    link: function(scope) {
        http.get('another/url/' + scope.id + '.json').then(function(result) {
            scope.name = result.data.name;
        }, function(err) {
            scope.name = "unknown";
        });
    }
}
}])

And the html code wich call the main directive :

<span my-main-directive param-id="myObject.id"></span>

When calling "other-directive", the "idFromServer" is not bind, and is "undefined", so it results to diplay "undefined".

I'm probably missing something stupid, but I don't see what ... (My piece of code is probabley not the best, I'm pretty new to angularjs, and specially the directives, and I tried a lot of ways to accomplish what I want.)

like image 683
Matthieu Lebigre Avatar asked Apr 17 '15 19:04

Matthieu Lebigre


People also ask

Which directive is used for data binding in AngularJS?

A - ng-bind directive binds the AngularJS Application data to HTML tags.

How can you bind an element to data in AngularJS?

Two-way Binding Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.

Does AngularJS use one way data binding?

No! AngularJS uses two way data binding.

Is AngularJS supports two way binding?

AngularJS creates a two way data-binding between the select element and the $ctrl. orderProp model. $ctrl. orderProp is then used as the input for the orderBy filter.


1 Answers

Per my comments, here's one way that might work, using a scope.$watch:

scope.$watch('id', function(id) {
    $http.get('some/url/' + id + '.json')
        .success(function (data) {
            scope.idFromServer = data;
        });
};

This would go inside the link function on the nested directive.

like image 154
Ben Black Avatar answered Sep 21 '22 05:09

Ben Black