【问题标题】:AngularJS Doesn't hold valueAngularJS 没有价值
【发布时间】:2016-05-18 14:43:49
【问题描述】:

我正在尝试为控制器上的角度服务设置一个值并从另一个控制器获取它,但该服务不保存该值。

App.js

var app = angular.module('Test', []);

app.service('editorPost', function() {

    this.ID = -1;

    this.setID = function(ID) {
        this.ID = ID;
    };

    this.getID = function() {
        return this.ID;
    };
});

第一个控制器

app.controller('DashboardController', ['$scope','editorPost',
function ($scope, editorPost) {
        $scope.loadEditor = function(link)
        {
            editorPost.setID(link.post.ID);
            // Displays the correct ID, obtained from the <a> clicked.
            console.log(editorPost.getID());
        };

    }]);

loadEditor 函数的调用方式如下:

<a href="/editor/editor.html" ng-click="loadEditor(this)">{{ post.webStory }}</a>

console.logging 值后,它会重定向到 editor.html 并显示来自服务的默认 ID 值。

第二个控制器(来自 editor/editor.html 的那个):

app.controller('EditorController', ['$scope','editorPost',
    function ($scope,editorPost)
{
    $scope.globals = globals;
    //Displays the default value, -1.
    console.log(editorPost.getID());
});

提前谢谢你。

【问题讨论】:

    标签: angularjs service controller


    【解决方案1】:

    当您在服务的方法中时,this 指的是该方法,而不是服务。将您的服务更改为如下所示:

    app.service('editorPost', function() {
    
        var service = this;
        service.ID = -1;
    
        service.setID = function(ID) {
            service.ID = ID;
        };
    
        service.getID = function() {
            return service.ID;
        };
    
        return service;
    });
    

    所以实际上,这是一个问题。第二个问题是您将使用您的 href 转到一个新的 HTML 页面。我猜你正在重新加载 Angular 和你的应用程序,它会重新实例化服务并将 id 设置回其默认值。在这种情况下,您确实需要使用 Angular 作为 SPA,否则您需要将 ID 作为 URL 参数传递并从那里获取它。

    【讨论】:

    • 在第二个控制器上仍然保持 -1 值。
    • 从未使用过,但我可以在 codepen 中从一个页面重定向到另一个页面吗?我会试着把它放上来。
    • 如果需要,只需将有问题的 2 个页面的 html 添加到您的问题中,我将在本地重新创建它。
    • 不知道这个codepen是否有意义,但确实如此。 codepen.io/anon/pen/qZGGVq?editors=1111 如果我想要的不可能,我怎么能通过 URL 传递值?
    • 在这种情况下,您可以使用角度路由“docs.angularjs.org/api/ngRoute”来避免这种行为
    【解决方案2】:

    我会说最好的方法是将函数像回调一样传递给服务,如下所示

    //EditorController

    editorPost.getID (function(data){
           console.log(data);
    });
    

    进入服务而不是使用返回,您需要类似以下内容

    app.service('editorPost', function() {
    
        this.ID = -1;
    
        this.setID = function(ID) {
            this.ID = ID;
        };
    
        this.getID = function(callback) {
            callback(this.ID);
        };
    });
    

    【讨论】:

    • 你好,我试过你说的,第二个控制器仍然输出-1值。
    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多