AngularJS:访问$ resource工厂定义中的范围

时间:2013-04-30 20:16:35

标签: angularjs coffeescript pusher

我正在运行一个包含Pusher的AngularJS应用程序,用于模型的实时更新。当推送器在工厂定义中发送AngularJS资源的更新数据时,我想在范围内触发操作。

我的资源定义如下:

TS.app.factory "Object", ($resource) ->
  Object = $resource("objects/:publicToken", {publicToken: "@public_token"}, {update: {method: "PUT"}})

  # Checks for updates to object data via Pusher.
  Object::watch = ->
    channelName = "private-12345"

    # See if we've already subscribed to this channel.
    channel = Namespace.pusher.channel(channelName)

    # If not, subscribe.
    channel ||= Namespace.pusher.subscribe(channelName)

    # Update data if we get new info from pusher.
    channel.bind "updated info", (data) =>
      # THIS GETS RUN WHEN PUSHER SENDS UPDATED DATA.
      for key, value of data
        this[key] = value
      # TRIGGER ACTION HERE

我想在此资源的范围内设置变量。我知道对于像$ get这样的方法,范围会自动更新,但我不知道在这种情况下如何做到这一点。我如何在这里访问范围?

如果还有其他更好的(或更多Angular-y)方法,那么它们是什么?

1 个答案:

答案 0 :(得分:3)

您绝对不希望您的服务了解您的模型或直接访问它们。听起来您似乎想要在服务上使用观察者模式,并让任何关心获取通知的控制器订阅您的服务。

以下是一个简单示例:http://jsfiddle.net/langdonx/sqCZz/

HTML

<div ng-app="app" ng-controller="testController">
    <div ng-repeat="notification in notifications">{{notification}}</div>
</div>

的JavaScript

angular.module('app', [])
    .factory('TestService', function () {
    var _subscribers = [];

    setInterval(function () {
        // every 1 second, notify all subscribers
        console.log(_subscribers);
        angular.forEach(_subscribers, function (cb) {
            cb('something special @ ' + new Date());
        });
    }, 2500);

    return {
        subscribe: function (cb) {
            _subscribers.push(cb);
        }
    };
})
    .controller('testController', function ($scope, TestService) {
    $scope.notifications = ['nothing yet'];

    TestService.subscribe(function (notification) {
        $scope.$apply(function () {
            $scope.notifications.push('got ' + notification);
        });
    });
});