AngularJS RouteParams

时间:2016-01-24 02:34:31

标签: javascript angularjs undefined

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

Cloud9

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

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"

编辑2

:好现在它可以工作,但我对如何在app.config上使用它感到困惑..我我的提供者是哈希:

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

当它进入控制器时我设置了哈希并得到了... 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"
        });




    }
])

现在我要做的是在我的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
  }
])

编辑3

我之前想说的是,我希望以某种方式在app.config()语句中配置随机生成的Hash。所以在我的app.config中。当USER在/ 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: '/'
      }); 
});

现在这里是提供者..

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

编辑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()

        });




    }
])

和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

1 个答案:

答案 0 :(得分:4)

您的代码中存在两个问题:

  1. &#34; roomController&#34;的定义

    app.controller('roomController', ["$scope", "Auth", "Ref", 
                   "AuthService", "roomService","$http", 
                   function($scope, Auth, Ref, AuthService, roomService, 
                   $http,box) {})
    
  2. 只需匹配参数及其声明,您就会看到错过了&#34;框的声明&#34;参数。正确的&#34; roomController&#34;定义应该是这样的:

    app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "box",
            function($scope, Auth, Ref, AuthService, roomService, $http,box)
    
    1. &#34;盒&#34;供应商。你定义了&#34; setColor&#34;方法作为提供程序的配置方法,但您尝试将其用作提供程序结果方法。更正后的版本应该是这样的:

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

      回答EDIT2:

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

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

      ...并允许您访问将其移至提供程序配置所需的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
                  }
              }
          }
      })
      

      回答EDIT3:

      现在我得到了你想做的事。而事实是,你正在努力做错:)。正确的方式更简单。您必须使用param configure route,例如:

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

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

      $routeParams.hash
      

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