从AngularJS中的服务内部访问$ scope属性 [英] Accessing $scope properties from inside a service in AngularJS

查看:69
本文介绍了从AngularJS中的服务内部访问$ scope属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在角度服务中创建一个构造函数,然后可以在我的不同角度控制器中使用它.问题是,从构造函数生成的对象需要访问$ scope对象上的属性之一才能正常运行.

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.

我的实现使用了我所追求的功能,但是它涉及将$ scope对象作为参数传递给构造函数.有没有更好的方法可以做到这一点?我目前的实施方式是否存在任何问题?

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:

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
    };
});

这是小提琴中的工作代码: http://jsfiddle.net/dBQz4/

Here is the working code in a fiddle: http://jsfiddle.net/dBQz4/

推荐答案

您真的不想在周围传递范围,它们是复杂的野兽.更重要的是,作为一般规则,最好是明确说明所传递的内容.如果您只需要一杯牛奶,请不要送牛.

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
    };
});

这篇关于从AngularJS中的服务内部访问$ scope属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆