iLemming
iLemming

Reputation: 36214

Accessing injected stuff in the template

If I want to do something stupid like this:

foo = 
   bar:'awesome bar'

app.constant "foo", foo

ctrl = ($scope, foo)->

<div ng-controller='ctrl'>
    {{foo.bar}} <!-- that won't work --> 
</div>

Is it possible somehow to access foo without putting it into the $scope?

Upvotes: 0

Views: 71

Answers (4)

Chad Robinson
Chad Robinson

Reputation: 4623

Also, it's worth mentioning that $rootScope is occasionally used for this because template expressions can walk up the scope chain to find things. This is really bad programming practice in a lot of cases... EXCEPT in some. Here are a few I've found that make some sense:

  • Angular ui-router docs suggest putting $state and $stateParams into $rootScope. They're used EVERYWHERE, so it's not necessarily evil because this is definitely a global, singleton service with identical functionality across the entire app.

  • If you have a few constants (I wouldn't want hundreds) with app-wide scope and you're just going to have to pass them down the scope chain anyway by constantly setting them into each controller you make (for instance, a page-wide variable that points you app to a Dev, QA, or Production box?)... The value of pretending any part of this is "local" to a scope is pretty low. All software development is a compromise. I think the reduced maintenance overhead and convenience might make this one worthwhile...

In both cases you still have that line of code somewhere (usually in your main or top-most controller)... but at least you only have it once. :)

Upvotes: 1

Gabe
Gabe

Reputation: 2137

Yes it is possible with the controllerAs syntax, though you still have to put foo on something.

<div ng-controller='ctrl as ctrl'>
    {{ctrl.foo.bar}}
</div>

And then in your controller

.controller('ctrl', (foo)->
  this.foo = foo;

Upvotes: 1

Michael Kang
Michael Kang

Reputation: 52867

Assuming 'foo' is an app constant, you can inject it into your directive and use it within your template function:

app.directive('test', function(foo) {
    return { 
        restrict: 'A',
        template: function() { 
            return foo.bar;
        } 

    }
});

HTML

<div ng-controller='ctrl' test>
</div>

This will render:

<div ng-controller='ctrl' test>
    awesome bar
</div>

Upvotes: 1

Will M
Will M

Reputation: 2145

No, $scope is the "glue" between a template and its controller. If you're injecting foo and want that to be directly available to your template, you must put it on the $scope.

This would also hold true for the link and controller functions of a directive.

Upvotes: 1

Related Questions