LVDM LVDM - 7 days ago 5
AngularJS Question

Do you always have to inherit service variable in controller in Angular?

i'm current starting to wrap my head around Angular, and i'm struggling with 2 things:

The first problem:
I have an controller 'AboutCtrl', which uses variables from a service 'Abstract'. Now what i want to do is set some basic variables in this service like: 'mobileMenuOpen'.

Now what i want is that 'AboutCtrl' uses the value from 'Abstract', now i've been searching around and i found this way to do it:

constructor (private $scope: IAboutScope, $rootScope, Abstract) {
console.log(Abstract);
$scope.mobileMenuOpen = Abstract.mobileMenuOpen;
}


Now what i'm wondering is, is there a way to automatically inherit all of these variables?

The second problem:
Is there a way to display a variable from 'Abstract' service in a view/index.html?

Example: in my about view i want to show mobileMenuOpen's value, now when i inherit the variable in the AboutCtrl like shown above it works, but how would i be able to do this without inheritance?

I've done some research about best practise and using services/factory seems best practise, if not some other examples would be greatly appreciated.

Answer

Let's say your service looks like this:

.service('abstract', function abstract(){
  this.mobileMenuOpen = false;
  this.someMethod = function(){
    //do the magic
    return 'cowabunga';
  };
})

If you assign the service to $scope by reference like this:

$scope.myAbstract = abstract 

then all the values of your service would be assigned to myAbstract and accessible in the templates as well, also it will be two-way binded

<p> Is the menu open: {{ myAbstract.mobileMenuOpen }} </p>
<p> {{ myAbstract.someMethod() }} was the ninja turtles war cry! </p>

Assignment like

$scope.mobileMenuOpen = abstract.mobileMenuOpen;

Would be assigning it by value so whatever change you make later in service will have no effect on $scope.mobileMenuOpen