Matt Cavanagh
Matt Cavanagh

Reputation: 518

How to access a property of a service via a bound controller variable

I'm attempting to access a property of a service via a bound controller variable, within a template, to no success.

Controller:

app.controller('VictoryController', function($scope, AlertStatisticsService) {
    $scope.AlertStats = AlertStatisticsService;
});

Service returns an object structured like this:

factory = {
    factionWins = {
        vs: 123,
        nc: 123,
        tr: 123
    }
}

The template is rendered as part of an Attribute directive:

app.directive('homeVictoryCard', function() {
    return {
        restrict: 'A',
        replace: true,
        scope : {
            empire: '@',
        },
        templateUrl: 'views/home/partials/victory.card.html'
    };
});

Which is called by the following HTML element:

<div home-victory-card empire="vs"></div>

In the template in question, I'm attempting to access the controller / service's object data via the empire variable, which is in scope of the template, like so:

{{ AlertStats.factionWins[empire] }}

I'm also trying to use it in various ng-hide and ng-shows, like:

ng-hide="AlertStats.factionWins[empire] > 0"

In Twig, I used to use attribute(AlertStats.factionWins, empire) to grab the information, but I don't know how to do it in Angular, and Google searches haven't returned anything useful.

Thanks in advance!

Upvotes: 0

Views: 51

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Since you have directive with isolated scope it doesn't inherit scope from parent controller so AlertStats isn't in directive scope

You could inject the factory into directive or pass another scope variable as attribute to directive

Example injecting factory

app.directive('homeVictoryCard', function(AlertStatisticsService) {
    return {
        restrict: 'A',
        replace: true,
        scope : {
            empire: '@',
        },
        templateUrl: 'views/home/partials/victory.card.html',
        link:function(scope){
           scope.AlertStats = AlertStatisticsService
        }
    };
});

Upvotes: 1

Related Questions