0

Is is possible to use property injection in angularJS?

Scenario
I know this will work

app
    .module('myapp')
    .config(function($stateProvider) {
        $stateProvider.state('the-state', {
            url: '/the/url',
            templateUrl: 'view.html',
            controller: 'ctrl',
            controllerAs: 'vm',
            resolve: {
                'boolFlag': function(service){return service.getBoolean();}
            }
        });
    })
    .service('service', function(){
        this.getBoolean = function() {return ...};
    })
    .controller('ctrl', function(boolFlag) {
        this.boolFlag = boolFlag;

        this.execute = function(){...};
    });


<div ng-show="vm.boolFalg">
  simple dynamic content
</div>
<button type="button" ng-click="vm.execute()">Click Me</button>

But it feels leaky. boolFlag` is only used in the view to show/hide content. Is there I way I can resolve the controller and set the boolFlag property on the controller instance? I assume providers or factories would be the way to go, but I'm going around in circles trying to make sense of it.

I envision it would look something like

app
    .module('myapp')
    .config(function($stateProvider) {
        $stateProvider.state('the-state', {
            url: '/the/url',
            templateUrl: 'view.html',
            controller: 'ctrl',
            controllerAs: 'vm',
        });
    })
    .provider('ctrlProvider', function(ctrlProvider, service) {
         var ctrl = ctrlProvider.$get/invoke/build/create();

         ctrl.boolFlag = service.getBoolean();

         return ctrl;
    })
    .service('service', function(){
        this.getBoolean = function() {return ...};
    })
    .controller('ctrl', function() {
        this.execute = function(){...};
    });

I could also be going about this the wrong way. Many controllers will need the boolFlag property. Maybe it should be part of a $parentScope? But I don't know how to code that.

Update I was thinking about this more last night. The boolFlag doesn't need to be associated to the controller at all. It only needs to be part of the scope. $scope.boolFlag = service.getBoolean();

The question then becomes, how can I populate $scope without the controller?

Jason Meckley
  • 7,589
  • 1
  • 24
  • 45

1 Answers1

0

you could use factory to maintain the value of boolFlag so that it is shared between the controllers. It is better to avoid using $parentScope. This explains how to proceed with that. If you need to set the value of factory initially you could also use it in app.config of your main module to set its value.

user93
  • 1,866
  • 5
  • 26
  • 45
  • Thank you. My end goal was to avoid injecting the value into the controller at all since it's only needed in the view. Thinking about this further, I only need boolFlag in the scope. not the controller. So how do I populate the scope without explicitly going through the controller? – Jason Meckley Jun 29 '17 at 12:24