Bruford
Bruford

Reputation: 521

Can't access properties of objects in Controller

I have a directive:

app.directive('bhHugeHeader',[function(){

    var link = function(scope, element, attrs, ctrl) {
        console.dir(ctrl);
        console.dir(ctrl.heroImgSrc);

        element.css({
            'min-height': '100%',
            'background-image': ctrl.heroImgSrc
        })
    }

    return {
        templateUrl: 'templates/hugeheader.html',
        controller: 'hugeHeaderController',
        controllerAs: 'hugeHeaderCtrl',
        restrict: 'E',
        replace: true,
        link: link
    }
}]);

Looking at those two console.dir calls - the first one returns an object which when I interrogate in the browser I can see has a property heroImgSrc with a value (which is a url to an image) but the second console.dir returns undefined.

What am I doing wrong? I guess my approach is flawed and I need to come at this in a different way but to me this seemed sound...until it didn't.

Upvotes: 1

Views: 687

Answers (2)

Bruford
Bruford

Reputation: 521

As it turns out this is an issue as to when the data becomes available. Given we're talking about Objects here, the data I was seeing in the Chrome Developer tools was just showing the current state.

The data is not available at the time the link function runs, so you need to add a watch - updated link function below:

var link = function(scope, element, attrs, ctrl) {

        scope.$watch(function() {return scope.hugeHeaderCtrl.heroImgSrc},function(newValue){
            if (newValue) {
                console.log(scope.hugeHeaderCtrl.heroImgSrc);
                element.css({
                    'min-height': '100%',
                    'background-image': 'url(' + scope.hugeHeaderCtrl.heroImgSrc + ')',
                    'background-size': 'cover'
                });
            }
        }); 
    }

Upvotes: 2

Silvinus
Silvinus

Reputation: 1445

Look at this blog : http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-6-using-controllers

If you use angular 1.3+ you must defined bindToController to true.

Upvotes: 0

Related Questions