简体   繁体   English

AngularJS RouteParams

[英]AngularJS RouteParams

I dont understand why but when i console.log() both box and box.color its telling me its undefined...I tried many different methods to solve this problem but it all failed. 我不明白为什么,但当我console.log()盒子和box.color它告诉我它未定义...我尝试了许多不同的方法来解决这个问题但它都失败了。

Cloud9 云9

Plunker Plunker

And here is script.js: 这是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)
            }
          }
    ])

roomController.js: 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"

EDIT 2 编辑2

: Ok Now it works but im confused on how to use it on app.config.. i My provider is Hash: :好的现在它有效,但我对如何在app.config上使用它感到困惑。我的提供者是Hash:

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




    }
])

And when it goes to the controller i set the hash and get the has ... roomControler.js: 当它进入控制器时我设置了哈希并得到了... 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" }); } ]) 

Now what i want to do is in my app.config() i want to say when it is in Hash.getHash() Go to template: , and controller: 现在我想要做的是在我的app.config()中我想说它何时在Hash.getHash()中转到模板:和控制器:

So something like this.... 所以像这样......

  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 } ]) 

EDIT 3 编辑3

What i was trying to say earlier was that i want to somehow configure the randomly generated Hash in my app.config() when statements. 我之前想说的是,我想以某种方式在我的app.config()语句中配置随机生成的Hash。 so in my app.config. 所以在我的app.config中。 WHEN the USER is in /RANDOMLYGENERATEDHASH have a template: '<h1>Test</h1>' . 用户在/ RANDOMLYGENERATEDHASH中有一个模板: '<h1>Test</h1>' This is what i tried but dosent workk... 这就是我尝试但是非常有用的...

It is the fourth one on the .when() Statements.. 这是.when()语句中的第四个..

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

And here is the provider now.. 这里是供应商..

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

EDIT 4 编辑4

Ok This is my roomcontroller.js Now..: (Important detail at bottom of controller) 好的这是我的roomcontroller.js现在...... :(控制器底部的重要细节)

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

and script.js(Note this is not the only ones i have. You can see all other on above link on Cloud9(Plunk not updated)): 和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 

There are two problems in your code: 您的代码中存在两个问题:

  1. Definition of "roomController" “roomController”的定义

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

Just match the parameters and their declarations and you will see that you missed a declaration for the "box" parameter. 只需匹配参数及其声明,您就会发现错过了“box”参数的声明。 The correct "roomController" definition should be like this: 正确的“roomController”定义应该是这样的:

app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "box",
        function($scope, Auth, Ref, AuthService, roomService, $http,box)
  1. "box" provider. “盒子”提供者。 You defined "setColor" method as the configuration method of provider, but you are trying to use it as a provider result method. 您将“setColor”方法定义为提供程序的配置方法,但您尝试将其用作提供程序结果方法。 The corrected version should be like this: 更正后的版本应如下所示:

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

Angular Providers 角度提供者

Answer to EDIT2: 回答EDIT2:

You defined HashProvider . 您定义了HashProvider To configure it in app.config you should pass argument as HashProvider (not just Hash, BUT when you will try to use it anywhere except app.config you should inject it as Hash). 要在app.config配置它,你应该将参数作为HashProvider传递(不仅仅是Hash,但是当你尝试在app.config以外的任何地方使用它时你应该将它作为Hash注入)。 So your app.config declaration should be like this: 所以你的app.config声明应该是这样的:

app.config(function ($routeProvider, $cookiesProvider, HashProvider)

...and to let you access the getHash method it's necessary to move it to the provider configuration, for example like this: ...并且为了让您访问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
            }
        }
    }
})

Answer to EDIT3: 回答EDIT3:

Now I got what you are trying to do. 现在我得到了你想做的事。 And the thing is that you are trying to do it wrong :). 而事实是,你正在努力做错:)。 The right way is more simple. 正确的方式更简单。 You have to configure route with param, for example like this: 您必须使用param 配置路由 ,例如:

.when('/:hash', {
    template: '<h1>TEST TEST</h1>',
    controller: 'any controller'
})

And place it just after your last route. 并将它放在最后一条路线之后。 After that, in controller you may access hash by using $routeParams object. 之后,在控制器中,您可以使用$routeParams对象访问哈希。 For example like this: 例如这样:

$routeParams.hash

And after that in controller you may analyze if it's right hash and do necessary stuff, or redirect user somewhere if hash is invalid. 然后在控制器中你可以分析它是否正确哈希并做必要的事情,或者如果哈希无效则将用户重定向到某个地方。

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

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