AngularJS失去参考服务的重新分配变量?变量、分配、AngularJS

由网友(笑出的泪 =)分享简介:我不知道那句更好的方法这个问题。我已经写了由两个控制器使用的基本服务。I didn't know a better way to phrase that question. I've written a basic service to be used by two controllers.的jsfiddle: h...

我不知道那句更好的方法这个问题。我已经写了由两个控制器使用的基本服务。

I didn't know a better way to phrase that question. I've written a basic service to be used by two controllers.

的jsfiddle: http://jsfiddle.net/aditya/2Nd8u/2/

JsFiddle: http://jsfiddle.net/aditya/2Nd8u/2/

点击通知按预期工作;它添加到阵列的通知。但是,重置打破它。点击任一按钮后,重置并没有做任何事情。有谁知道这是怎么回事吗?

Clicking 'notify' works as expected; it adds a notification to the array. But 'reset' breaks it. Clicking either button after 'reset' doesn't do anything. Does anyone know what's going on here?

PS。我认为这是与角丢失,因为 notifs 引用正在重新分配(技术上),所以我写了getter和setter方法​​,但即使清空阵列包括 POP() ING,直到它是空的,这似乎不是很有效。

PS. I think it has something to do with Angular losing the reference since notifs is being re-assigned (technically), so I wrote getters and setters, but even emptying the array involves pop()ing till it's empty, which doesn't seem very efficient.

Plunkr如果是的jsfiddle下来: http://plnkr.co/edit/mzfLLjFXCwsxM5KDebhc

Plunkr if JsFiddle is down: http://plnkr.co/edit/mzfLLjFXCwsxM5KDebhc

推荐答案

我改变了你的服务,这样的:

I changed your service to this:

.factory("notificationService", function(){
    var notifications = [];
    return {
        notifs: notifications,
        clear: function(){
            angular.copy([], notifications);
        },
        get: function(){ 
            return notifs; 
        }
    }
})

和控制器:

$scope.reset = function(){
        console.log("reset");
        notificationService.clear();
        console.log(notificationService);
    }

和它为我工作。

当然它应该是一点点整洁,在代替notifs你应该有一个get,并添加和删除的方法,但我只是想告诉你,其中code改变。在 angular.copy 是可以确保的更改角的生命周期内取得的方法。

Naturally it should be a little bit tidier, in that instead of notifs you should have a get, and add and a remove method, but i just wanted to show you where the code changed. The angular.copy is the method that makes sure the changes are made within angular's lifecycle.

正如你不能绑定变量,但只有方法,你可以这样做:

As you can't bind variable but only methods, you could do this:

$ scope.getNotifications = notificationService.get;

这应该工作。

阅读全文

相关推荐

最新文章