Accessing $scope properties from inside a service in AngularJS

半世苍凉 提交于 2019-12-13 19:56:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!