How to access an Angular service object from a template?

I have 2 controllers: one for the menu (a dynamic list of elements that we can add / remove), and one for ng-view.

I need to access menu items from an ng-view controller. Therefore, as I understand it, I have to create a service, so the menu objects will be available in any controller, I just need to enter it.

Done.

But!

I need these objects in rendering. So, should I put menu items on both controllers? This is ugly: I have to update its value every time I update elements in a service. Heck.

So, he is currently working with rootScope and a service that has an update / add / remove AJAX list item processing method. But I think something is wrong here.

Any tips?

+3
source share
1 answer

If you have data, you can use the value. Add a value to each of your controllers and save it in your area, and then specify the value property in your template. If you use the Service, you can do almost the same thing. My example shows one solution using each.

See this example: http://plnkr.co/edit/qTbSjnf6Q2FVDurGZhKd

<div ng-controller="MainCtrl">
  <input ng-model="mainVal.value"></input>
  <input ng-model="mainSvcVal.value"></input>
</div>
<div ng-controller="OtherCtrl">
  <input ng-model="otherVal.value"></input>
  <input ng-model="otherSvcVal.value"></input>
</div>

var app = angular.module('plunker', []);

app.value('MyValue', {value: "Hello There"});

app.service('MyService', function() {
  this.myData = {
    value: "Goodbye"
  }
});

app.controller('MainCtrl', function($scope, MyValue, MyService) {
  $scope.mainVal = MyValue;
  $scope.mainSvcVal = MyService.myData;
});

app.controller('OtherCtrl', function($scope, MyValue, MyService) {
  $scope.otherVal = MyValue;
  $scope.otherSvcVal = MyService.myData;
});

It should be noted that if you reassign MyService.myData to a new object, this will break the connection.

+3
source

All Articles