AngularJS没有价值

特洛伊兹

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

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

先感谢您。

迈克·费特曼

当您在服务中的方法内部时,它是指该方法,而不是服务。更改您的服务,使其看起来像这样:

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参数传递并从那里获取它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章