AngularJS RouteParams

ama*_*el2 11 javascript undefined angularjs

我不明白为什么,但当我console.log()盒子和box.color它告诉我它未定义...我尝试了许多不同的方法来解决这个问题但它都失败了.

云9

Plunker

这是script.js:

var app = angular.module('LoginApp', ["firebase", "ngRoute", "ngCookies"])


app.provider("box", function ()
{
    var hex = "SomeColor";
    var UID = 3;
    return {
        setColor: function (value)
        {
            UID = value
        },
        $get: function ()
        {
            return {
                color: hex
            }
        }
    }
})

app.config(function ($routeProvider, $cookiesProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'HtmlFiles/registration.html',
        controller: 'regController'
      })
     .when('/logIn', {
        templateUrl: 'HtmlFiles/login.html',
        controller: 'loginController'
      })

      .when('/Chat', {
        templateUrl: 'HtmlFiles/Chat.html',
        controller: 'chatController'

      })
      .when('/Test' , {
        template: '<h3>This is just a testing phase</h3>',
        controller: 'Testing'
      })

      .when('/userSettings', {
        templateUrl: 'HtmlFiles/userSettings.html',
        controller: 'userSettingsController'

      })

      .when('/room', {
        templateUrl: 'HtmlFiles/room.html',
        controller: 'roomController'
      })

      .otherwise({
        redirectTo: '/'
      }); 
});

app.controller('Testing', ["$scope","roomService", "roomProvider",  function($scope, roomService, roomProvider){
  console.log("This is from the Controller Service: " + roomService.room.roomUID)
  console.log("This is from the Controller Provider: " + roomProvider.$get)
  }
])
app.factory("Auth", ["$firebaseAuth",
  function($firebaseAuth) {
    var ref = new Firebase("https://chattappp.firebaseio.com/");
    return $firebaseAuth(ref);
  }
]);

app.factory("Ref", function(){
   var ref = new Firebase("https://chattappp.firebaseio.com/")
   return ref;
})

app.factory("UniPosts" , function(){
  var ref = new Firebase("https://postss.firebaseio.com/")
   return ref;
});

app.service('getCookieService', ["$cookieStore", "$scope", 
          function($cookieStore, $scope){
            this.getCookie = function(name){
              $cookieStore.get(name)
            }
          }
    ])
Run Code Online (Sandbox Code Playgroud)

roomController.js:

app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http",
    function($scope, Auth, Ref, AuthService, roomService, $http,box) {
    // Sweet Alert :)
     function generateRandomStringToken(length) {
            var string = "";
            var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for (var i = 0; i < length; i++){
                string += characters.charAt(Math.floor(Math.random() * characters.length));
            }
            return string;
        }

        swal({
            title: "Room",
            text: "What do you want your room name to be?",
            type: "input",
            showCancelButton: true,
            closeOnConfirm: false,
            animation: "slide-from-top",
            inputPlaceholder: "Write something"
        }, function(inputValue) {
            if (inputValue === false) return false;
            if (inputValue === "") {
                swal.showInputError("You need to write something!");
                return false
            }
            swal("Nice!", "You wrote: " + inputValue, "success");
             $scope.$apply(function () {
            $scope.roomNameModel = inputValue
            });

           console.log($scope.roomNameModel)
    var redirectPage = generateRandomStringToken(10)
     console.log("User gets redirected to : " + redirectPage + " ...")
     roomService.setRoomUID(redirectPage);
     console.log(roomService.room.roomUID)
     console.log(box) //Undefined...
     console.log("From Provider : " + box.color)//box.color is undefined..


        });




    }
])
    //window.location.hash = "/Test"
Run Code Online (Sandbox Code Playgroud)

编辑2

:好的现在它有效,但我对如何在app.config上使用它感到困惑.我的提供者是Hash:

app.provider("Hash", function ()
    {
        var UID = 0;
        return {
            $get: function ()
            {
                return {
                    setHash: function (value)
                    {
                        UID = value;
                    },
                    getHash: function()
                    {
                        return UID;
                    }
                }
            }
        }
    })
Run Code Online (Sandbox Code Playgroud)

当它进入控制器时我设置了哈希并得到了... roomControler.js:

app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "Hash",
        function($scope, Auth, Ref, AuthService, roomService, $http,Hash) {
    // Sweet Alert :)
     function generateRandomStringToken(length) {
            var string = "";
            var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for (var i = 0; i < length; i++){
                string += characters.charAt(Math.floor(Math.random() * characters.length));
            }
            return string;
        }

        swal({
            title: "Room",
            text: "What do you want your room name to be?",
            type: "input",
            showCancelButton: true,
            closeOnConfirm: false,
            animation: "slide-from-top",
            inputPlaceholder: "Write something"
        }, function(inputValue) {
            if (inputValue === false) return false;
            if (inputValue === "") {
                swal.showInputError("You need to write something!");
                return false
            }
            swal("Nice!", "You wrote: " + inputValue, "success");
             $scope.$apply(function () {
            $scope.roomNameModel = inputValue
            });

           console.log($scope.roomNameModel)
    var redirectPage = generateRandomStringToken(10)
     console.log("User gets redirected to : " + redirectPage + " ...")
     roomService.setRoomUID(redirectPage);
     console.log(roomService.room.roomUID);
     Hash.setHash(redirectPage);
     console.log("From Provider : " + Hash.getHash())
    window.location.hash = "/Test"
        });




    }
])
Run Code Online (Sandbox Code Playgroud)

现在我想要做的是在我的app.config()中我想说它何时在Hash.getHash()中转到模板:和控制器:

所以像这样......

    app.config(function ($routeProvider, $cookiesProvider, Hash) {
        $routeProvider.
         when('/' + Hash.getHash(), {
               template: '<h4> Your in Room',
               controller: 'Test
                })
});

app.controller('Testing', ["$scope","roomService","Hash",function($scope, roomService, Hash){
  console.log("This is from the Controller Service: " + roomService.room.roomUID)
  console.log(Hash.getHash())//This Logs right. :D
  }
])
Run Code Online (Sandbox Code Playgroud)

编辑3

我之前想说的是,我想以某种方式在我的app.config()语句中配置随机生成的Hash.所以在我的app.config中.用户在/ RANDOMLYGENERATEDHASH中有一个模板:'<h1>Test</h1>'.这就是我尝试但是非常有用的...

这是.when()语句中的第四个..

app.config(function ($routeProvider, $cookiesProvider, HashProvider){
    $routeProvider
      .when('/', {
        templateUrl: 'HtmlFiles/registration.html',
        controller: 'regController'
      })
     .when('/logIn', {
        templateUrl: 'HtmlFiles/login.html',
        controller: 'loginController'
      })

      .when('/Chat', {
        templateUrl: 'HtmlFiles/Chat.html',
        controller: 'chatController'

      })
      .when('/' + HashProvider , {
        templete: '<h1>Test</h1>'
      })
      .when('/userSettings', {
        templateUrl: 'HtmlFiles/userSettings.html',
        controller: 'userSettingsController'
      })
      .when('/room', {
        templateUrl: 'HtmlFiles/room.html',
        controller: 'roomController'
      })

      .otherwise({
        redirectTo: '/'
      }); 
});
Run Code Online (Sandbox Code Playgroud)

这里是供应商..

app.provider("Hash", function ()
{
    var UID = 0;
    var _getHash = function()
    {
        return UID;
    };
    return {
        getHash: _getHash,
        $get: function ()
        {
            return {
                setHash: function (value)
                {
                    UID = value;
                },
                getHash: _getHash
            }
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

编辑4

好的这是我的roomcontroller.js现在...... :(控制器底部的重要细节)

app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "Hash","$routeParams",
        function($scope, Auth, Ref, AuthService, roomService, $http,Hash, $routeParams) {
    // Sweet Alert :)
     function generateRandomStringToken(length) {
            var string = "";
            var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for (var i = 0; i < length; i++){
                string += characters.charAt(Math.floor(Math.random() * characters.length));
            }
            return string;
        }

        swal({
            title: "Room",
            text: "What do you want your room name to be?",
            type: "input",
            showCancelButton: true,
            closeOnConfirm: false,
            animation: "slide-from-top",
            inputPlaceholder: "Write something"
        }, function(inputValue) {
            if (inputValue === false) return false;
            if (inputValue === "") {
                swal.showInputError("You need to write something!");
                return false
            }
            swal("Nice!", "You wrote: " + inputValue, "success");
             $scope.$apply(function () {
            $scope.roomNameModel = inputValue
            });

           console.log($scope.roomNameModel)
    var redirectPage = generateRandomStringToken(10)
     console.log("User gets redirected to : " + redirectPage + " ...")
     roomService.setRoomUID(redirectPage);
     console.log(roomService.room.roomUID);
     Hash.setHash(redirectPage);
     console.log("From Provider : " + Hash.getHash())
     $routeParams.hash = Hash.getHash()

        });




    }
])
Run Code Online (Sandbox Code Playgroud)

和script.js(注意这不是我唯一拥有的.你可以在Cloud9上看到上面链接上的所有其他内容(Plunk未更新)):

var app = angular.module('LoginApp', ["firebase", "ngRoute", "ngCookies", 'ngMessages'])


app.provider("Hash", function ()
{
    var UID = 0;
    var _getHash = function()
    {
        return UID;
    };
    return {
        getHash: _getHash,
        $get: function ()
        {
            return {
                setHash: function (value)
                {
                    UID = value;
                },
                getHash: _getHash
            }
        }
    }
})

app.config(function ($routeProvider, $cookiesProvider, HashProvider){
    $routeProvider
      .when('/', {
        templateUrl: 'HtmlFiles/registration.html',
        controller: 'regController'
      })
     .when('/logIn', {
        templateUrl: 'HtmlFiles/login.html',
        controller: 'loginController'
      })

      .when('/Chat', {
        templateUrl: 'HtmlFiles/Chat.html',
        controller: 'chatController'

      })
    .when('/:Hash', {
            template: '<h1>TEST TEST</h1>',
            controller: 'any controller'
        })
      .when('/userSettings', {
        templateUrl: 'HtmlFiles/userSettings.html',
        controller: 'userSettingsController'
      })
      .when('/room', {
        templateUrl: 'HtmlFiles/room.html',
        controller: 'roomController'
      })

      .otherwise({
        redirectTo: '/'
      }); 
});

app.controller('Testing', ["$scope","roomService","Hash",function($scope, roomService, Hash){
  console.log("This is from the Controller Service: " + roomService.room.roomUID)
  console.log(Hash.getHash())
  }
])
app.factory("Auth", ["$firebaseAuth",
  function($firebaseAuth) {
    var ref = new Firebase("https://chattappp.firebaseio.com/");
    return $firebaseAuth(ref);
  }
]);

app.factory("Ref", function(){
   var ref = new Firebase("https://chattappp.firebaseio.com/")
   return ref;
})

app.factory("UniPosts" , function(){
  var ref = new Firebase("https://postss.firebaseio.com/")
   return ref;
});

app.service('getCookieService', ["$cookieStore", "$scope", 
          function($cookieStore, $scope){
            this.getCookie = function(name){
              $cookieStore.get(name)
            }
          }
    ])




  [1]: https://ide.c9.io/amanuel2/chattapp
  [2]: https://plnkr.co/edit/ToWpQCw6GaKYkUegFjMi?p=preview
Run Code Online (Sandbox Code Playgroud)

Ale*_*hov 4

您的代码中有两个问题:

  1. “房间控制器”的定义

    app.controller('roomController', ["$scope", "Auth", "Ref", 
                   "AuthService", "roomService","$http", 
                   function($scope, Auth, Ref, AuthService, roomService, 
                   $http,box) {})
    
    Run Code Online (Sandbox Code Playgroud)

只需匹配参数及其声明,您就会发现您错过了“box”参数的声明。正确的“roomController”定义应该是这样的:

app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "box",
        function($scope, Auth, Ref, AuthService, roomService, $http,box)
Run Code Online (Sandbox Code Playgroud)
  1. “盒子”提供商。您将“setColor”方法定义为提供程序的配置方法,但您尝试将其用作提供程序结果方法。修正后的版本应该是这样的:

    app.provider("box", function ()
    {
        var hex = "SomeColor";
        var UID = 3;
        return {
            $get: function ()
            {
                return {
                    color: hex,
                    setColor: function (value)
                    {
                        UID = value
                    }
                }
            }
        }
    })
    
    Run Code Online (Sandbox Code Playgroud)

角度提供者

对EDIT2的回答:

你定义的HashProvider. 要在其中配置它,app.config您应该将参数传递为HashProvider(不仅仅是哈希,但是当您尝试在除 app.config 之外的任何地方使用它时,您应该将其作为哈希注入)。所以你的 app.config 声明应该是这样的:

app.config(function ($routeProvider, $cookiesProvider, HashProvider)
Run Code Online (Sandbox Code Playgroud)

...并且为了让您访问该getHash方法,有必要将其移至提供程序配置,例如如下所示:

app.provider("Hash", function ()
{
    var UID = 0;
    var _getHash = function()
    {
        return UID;
    };
    return {
        getHash: _getHash,
        $get: function ()
        {
            return {
                setHash: function (value)
                {
                    UID = value;
                },
                getHash: _getHash
            }
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

对EDIT3的回答:

现在我明白了你想做的事。问题是你试图做错事:)。正确的方法更简单。您必须使用参数配置路由,例如如下所示:

.when('/:hash', {
    template: '<h1>TEST TEST</h1>',
    controller: 'any controller'
})
Run Code Online (Sandbox Code Playgroud)

并将其放在最后一条路线之后。之后,在控制器中您可以使用$routeParams对象访问哈希。例如这样:

$routeParams.hash
Run Code Online (Sandbox Code Playgroud)

之后,在控制器中,您可以分析它是否是正确的哈希并执行必要的操作,或者如果哈希无效,则将用户重定向到某个地方。

  • 也许我错了。也许..但现在看来你不想理解我向你建议的内容以及它是如何工作的以及为什么它有效。我在你的 Cloud9 中看到的只是复制和粘贴,有很多印刷错误,而且看起来你没有仔细阅读有关 Angular Routing 的内容。请阅读它并尝试完全理解它是如何工作的以及为什么会工作。如果没有这个,我纠正每个印刷错误就没有意义。 (2认同)