0

first time asker. Apologies if my jargon isn't quite right I'm new to angularjs

I have a controller which gets a list of products with a HTTP call

contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams',     '$http', '$location',
    function ($scope, $routeParams, $http, $location)
    {
        $http.get('products').success(function (products)
        {
            $scope.productList = products
        })
    }

And a directive which I would like to have access to that product list.

contractManagementControllers.directive("priceBands",function($http)
{
    return {
        scope: true,
        restrict: 'AE',
        replace: 'true',
        templateUrl: 'Partials/PriceBand.html',
        link: function ($scope, ele, attrs, c)
        {
            // use $scope.productList
        }
});

My issue is with the order in which things happen. The controller function runs first, followed by the directive link function, followed by the callback which sets the product list. As such $scope.productList is undefined in the directive link function and gives an error

Is there a way to force the link function to wait until the callback has completed?

2 Answers 2

1

Set default value to productList in order not get error about undefined variable

contractManagementControllers.controller('PriceBandsCtrl', ['$scope', '$routeParams',     '$http', '$location',
    function ($scope, $routeParams, $http, $location)
    {
        $scope.productList = [];
        $http.get('products').success(function (products)
        {
            $scope.productList = products
        })
    }

and then watch for changes of the productList in directive:

contractManagementControllers.directive("priceBands",function($http)
{
    return {
        scope: true,
        restrict: 'AE',
        replace: 'true',
        templateUrl: 'Partials/PriceBand.html',
        link: function ($scope, ele, attrs, c)
        {
            $scope.watch('productList', function(newValue, oldValue) {
                //Perform here if you need
            });
        }
});
Sign up to request clarification or add additional context in comments.

1 Comment

That's great thanks, although turns out the watch needs a dollar sign $scope.$watch
0

no need of waiting for callback in angularjs. just put the $scope.productList=[]; in your controller as first line. it will not give undefined to directive.

In your directive link function just write the $watch function to watch changes in element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.