Wazime
Wazime

Reputation: 1688

angular directive ng-repeat scope and Service

I am trying to create angular directive whom can run alone without a Controller, so I can set it anywhere I want, without adding the model to the controller. The code is fairly simple:

App.directive('ngdPriceWithCurrencySelect',['CurrenciesService' ,function (CurrenciesService) {
    return {
        restrict: 'E',
        replace: true,
        scope: true,
        link: function ($scope, $element, $attrs) {
            $scope.currencies = CurrenciesService.getData();
            $scope.$watch('currencies', function(newValue, oldValue){
                console.log($scope.currencies);
            });
        },
        template: '<select>\n\
                    <option ng-repeat="currency in currencies">{{currency.cur_name_he}}</option>\n\
                </select>'
    }
}]);

The Service actually return the data and the console.log($scope.currencies) shows object with the currencies. but the repeater is not runing and I am not getting the result I want.

I thought this might be a scope problem, but I can't find a way to see the scope itsel. (angularjs batarang is not working in version 1.3+)

the problem can be in the Service as well so I am giving the service code:

App.service('CurrenciesService', ["$http", "$q", function ($http, $q) {
        var service = {
            returnedData: [],
            dataLoaded: {},
            getData: function (forceRefresh) {
                var deferred = $q.defer();
                if (!service.dataLoaded.genericData || forceRefresh){
                    $http.get("data/currencies").success(function (data) {
                        angular.copy(data, service.returnedData)
                        service.dataLoaded.genericData = true;
                        deferred.resolve(service.returnedData);
                    });
                }
                else{
                    deferred.resolve(service.returnedData);
                }
                return deferred.promise;
            },
        };
        service.getData();
        return service;
    }]);

here is a JS fiddle for testing it: http://jsfiddle.net/60c0305v/2/

Upvotes: 0

Views: 73

Answers (1)

eladcon
eladcon

Reputation: 5825

Your service returns a promise, not the data itself. You need to set a function for when the service resolves the promise:

link: function ($scope, $element, $attrs) {
    // waiting for the service to resolve the promise by using the done method 
    CurrenciesService.getData().then(function(data) {
        $scope.currencies = data;
    });
    $scope.$watch('currencies', function(newValue, oldValue){
        console.log($scope.currencies);
    });
}

Check this fiddle

Upvotes: 3

Related Questions