0

Is there a way to inject automatically a dependency (or a resolve) in the $scope without manually append it to $scope ? (with or without UI-Router)

Would the "controllerAs" syntax be of any help ?

.config(['$stateProvider',
    function($stateProvider) {

        $stateProvider
            .state('test', {
                url: '/test',
                templateUrl: 'test.tpl.html',
                controller: 'TestCtrl',
            })
        ;
    }
])
.controller('TestCtrl', ['$scope', 'myService',
    function($scope, $rootScope, accruals, myService) {
        $scope.myService= myService; // how can I avoid this every time ?
    }
])

Thanks

Jscti
  • 14,096
  • 4
  • 62
  • 87
  • Why would you even want to do that? Why do you use `$scope.myService= myService` and not simply use `myService` directly? – dirkk Jul 24 '14 at 08:55
  • Well .. my service handle the logic (that I don't want to put in a controller) and it's mainly my templates that call that service ... what's wrong with this ? – Jscti Jul 24 '14 at 09:03
  • Nothing, but why are you binding your service into the controller? If using the service, simply use `myService` directly, instead of `$scope.myService`. – dirkk Jul 24 '14 at 09:04
  • And how do I access myService in my template If I don't bind it to the $scope ? – Jscti Jul 24 '14 at 09:06
  • 2
    @Bixi Well, you shouldn't ;) – Yoshi Jul 24 '14 at 09:09
  • What Yoshi said :) Instead, put a function into your controller which uses the service, something like `$scope.getValue = function() { return myService.doSomethingAwesome();}` and call `getValue()` in your template – dirkk Jul 24 '14 at 09:11
  • 1
    Ok that's interesting, could you elaborate on this ? You mean it's better practice to bind object/function/just-what-I-need to the $scope instead of the full service ? – Jscti Jul 24 '14 at 09:11
  • @Bixi Exactly. Think about reusing the service. Binding it directly to one controller (e.g. injecting it's api) you would predetermine how the next controller/service would have to use that service. And I think that's really a bad code smell. – Yoshi Jul 24 '14 at 09:14
  • 1
    @Bixi I do not want to say what is good or bad... but to solve your issue, you should/could use state nesting. If you assing to parent $scope something (method, object...) it will be available on a child $scope... and in fact that's how the ui-router was intended to work... profit from state and scope nesting... Maybe this could help http://stackoverflow.com/a/20558850/1679310 – Radim Köhler Jul 24 '14 at 09:16
  • Yeah I totally agree, It has that smell but I couldn't find where :) Thanks for your feedbacks! @Radim Köhler Thanks for that, it could be usefull to know – Jscti Jul 24 '14 at 09:16

0 Answers0