Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a controller trait in AngularJS

I want to give a set of controllers access to methods and properties defined in a trait. Right now the best implementation I have come up with is:

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

app.controller('MainCtrl', function($scope, CtrlTrait) {
  $scope.name = CtrlTrait.presetName;
  CtrlTrait.setGreeting.call($scope, 'Hello');
});

app.service('CtrlTrait', function() {
  this.setGreeting = function(greeting) { this.greeting = greeting; }
  this.presetName = 'tom';
});

Plunkr Code

This is fine, but I would like the properties and method to be accessible via the controller's $scope without having to manually create the alias in each controller. I want to be able to use the properties and method from the template just by having injected the service into the controller.

Is this possible, or do I have to create a [wrapper around]/[provider for] $scope like $specialCtrlScope that presets the properties and methods I want?

like image 246
km6zla Avatar asked Jan 11 '23 05:01

km6zla


1 Answers

You can try using angular.extend like this: angular.extend($scope,CtrlTrait); It will allows us to use in the $scope the same functions that your service. So, you can use the function directly in your html like this:

 <button ng-click="setGreeting('Good bye! ')">Good Bye</button>

Here is your plunker demo adapted:

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

app.controller('MainCtrl', function($scope, CtrlTrait) {
  $scope.name = CtrlTrait.presetName;
 // CtrlTrait.setGreeting.call($scope, 'Hello');
  angular.extend($scope,CtrlTrait);
  $scope.setGreeting('Hello World');
});

app.service('CtrlTrait', function() {
  this.setGreeting = function(greeting) { this.greeting = greeting; }
  this.presetName = 'tom';
});

http://plnkr.co/edit/BENS78mjFfpc6VCEtgK8?p=preview

like image 181
Dalorzo Avatar answered Jan 17 '23 13:01

Dalorzo