问题
I am trying to create a constructor function inside an angular service, which I could then use inside of my different angular controllers. The problem is, my object generated from the constructor needs access to one of the properties on my $scope object in order to function correctly.
I have the implementation working with the functionality I am after, but it involves passing the $scope object into the constructor function as a parameter. Is there a better way to accomplish this? Are there any issues with the way I currently have it implemented?
HTML:
<div ng-app="myApp">
<div ng-controller="myController">
<input type="text" ng-model="hello" />
<br/>{{hello}}
<br/>{{helloSayer.hello}}
<br/>{{helloSayer.helloLength()}}
</div>
</div>
JavaScript:
var myApp = angular.module('myApp', []);
myApp.controller('myController', function myController($scope, myService) {
$scope.hello = 'Hello from controller';
$scope.helloSayer = new myService.HelloSayer($scope);
});
myApp.factory('myService', function () {
var HelloSayer = function (controllerScope) {
this.hello = 'Hello from service';
this.helloLength = function () {
return controllerScope.hello.length;
};
};
return {
HelloSayer: HelloSayer
};
});
Here is the working code in a fiddle: http://jsfiddle.net/dBQz4/
回答1:
You really do not want to be passing scopes around, they are complicated beasts. More to the point, as a general rule it is a good idea to be explicit about what you are passing around. Don't send the cow if you only need a glass of milk.
var myApp = angular.module('myApp', []);
myApp.controller('myController', function myController($scope, myService) {
$scope.hello = 'Hello from controller';
$scope.helloSayer = new myService.HelloSayer($scope.hello);
});
myApp.factory('myService', function () {
var HelloSayer = function (controller_hello) {
this.hello = 'Hello from service';
this.helloLength = function () {
return controller_hello.length;
};
};
return {
HelloSayer: HelloSayer
};
});
回答2:
It makes perfect sense to pass in the scope that you need to operate on. This will also simplify unit testing the service.
来源:https://stackoverflow.com/questions/24332262/accessing-scope-properties-from-inside-a-service-in-angularjs