简体   繁体   English

如何在Angular.JS中的$ routeProvider配置内访问工厂数据对象?

[英]How to access a factory data object inside of a $routeProvider config in Angular.JS?

I am trying to create an Angular.JS calculator, that will return the user back to the root page if a certain factory Data object is empty. 我正在尝试创建一个Angular.JS计算器,如果某个工厂Data对象为空,它将使用户返回到根页面。 My issue is that I cannot figure out how to access the Data.Terms object to see if it is empty inside of the $routeProvider configuration under the /condition path. 我的问题是我无法弄清楚如何访问Data.Terms对象以查看在/condition路径下的$routeProvider配置内部它是否为空。

In my code below, the section that says if (!Data.Terms) is not working. 在下面的代码中,说明if (!Data.Terms)是否无效的部分。 I want it to return the value of Terms stored in the factory Data function: 我希望它返回存储在工厂数据函数中的术语的值:

// Creating the module
var myApp = angular.module("app-calculator", ["calculatorControls", "ngRoute"])
    .config(function ($routeProvider) {

        $routeProvider.when("/", {
            controller: "termsController",
            controllerAs: "vm",
            templateUrl: "/content/templates/termsView.html"
        });

        $routeProvider.when("/condition", {
            controller: "conditionController",
            controllerAs: "vm",
            templateUrl: "/content/templates/conditionView.html",
            resolve: {
                mess: function ($location) {

                    // Check if the Data.Terms field has been completed,
                    // if not then return to the root path.
                    if (!Data.Terms) {
                        $location.path('/');
                    }
                    //

                }
            }
        });

// my Data
myApp.factory('Data', function () {
    var Terms = '';

    return {
        Terms: Terms,
    }
})

you should inject Data as dependency in your resolve section. 您应该在您的“解决”部分中将Data作为依赖项注入。

var myApp = angular.module("app-calculator", ["calculatorControls", "ngRoute"])
    .config(function ($routeProvider) {

        $routeProvider.when("/", {
            controller: "termsController",
            controllerAs: "vm",
            templateUrl: "/content/templates/termsView.html"
        });

        $routeProvider.when("/condition", {
            controller: "conditionController",
            controllerAs: "vm",
            templateUrl: "/content/templates/conditionView.html",
            resolve: {
                mess: function ($location, Data) {

                    // Check if the Data.Terms field has been completed,
                    // if not then return to the root path.
                    if (!Data.Terms) {
                        $location.path('/');
                    }
                    //

                }
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM