首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS RouteParams

AngularJS RouteParams
EN

Stack Overflow用户
提问于 2016-01-24 02:34:30
回答 1查看 776关注 0票数 11

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

Cloud9

柱塞

下面是script.js:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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上使用它感到困惑。我的提供者是Hash:

代码语言:javascript
复制
app.provider("Hash", function ()
    {
        var UID = 0;
        return {
            $get: function ()
            {
                return {
                    setHash: function (value)
                    {
                        UID = value;
                    },
                    getHash: function()
                    {
                        return UID;
                    }
                }
            }
        }
    })

当它到达控制器时,我设置哈希并得到哈希.roomControler.js:

代码语言:javascript
复制
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()中时,转到模板:和控制器:

所以像这样的..。

代码语言:javascript
复制
    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() when语句中以某种方式配置随机生成的Hash。所以在我的app.config里。当用户在/RANDOMLYGENERATEDHASH中时,有一个模板:'<h1>Test</h1>'。这是我试过的,但剂量有效.

它是.when()语句上的第四个语句。

代码语言:javascript
复制
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: '/'
      }); 
});

现在是供应商..。

代码语言:javascript
复制
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现在..:(控制器底部的重要细节)

代码语言:javascript
复制
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未更新):

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-28 12:31:49

代码中有两个问题:

  1. "roomController“的定义 App.controller(“房间控制器”,["$scope","Auth","Ref","AuthService","roomService","$http",函数($scope,Auth,Ref,AuthService,roomService,$http,box) ){}

只要匹配参数和它们的声明,您就会发现忽略了"box“参数的声明。正确的"roomController“定义应该如下所示:

代码语言:javascript
复制
app.controller('roomController', ["$scope", "Auth", "Ref", "AuthService", "roomService","$http", "box",
        function($scope, Auth, Ref, AuthService, roomService, $http,box)
  1. “盒子”提供商。您将"setColor“方法定义为提供程序的配置方法,但您正在尝试将其用作提供程序结果方法。修正后的版本应如下: app.provider("box",函数() { var十六进制= "SomeColor";var UID = 3;返回{ $get:函数() {返回{颜色:十六进制,setColor:函数(值){ UID = value })

角度提供者

对EDIT2的回答:

您定义了HashProvider。要在app.config中配置它,您应该将参数作为HashProvider传递(不仅仅是Hash,而且当您尝试在除app.config之外的任何地方使用它时,您应该将其作为Hash注入)。因此,您的app.config声明应该如下所示:

代码语言:javascript
复制
app.config(function ($routeProvider, $cookiesProvider, HashProvider)

为了让您访问...and方法,有必要将其移动到提供者配置,例如:

代码语言:javascript
复制
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进行配置路由,例如:

代码语言:javascript
复制
.when('/:hash', {
    template: '<h1>TEST TEST</h1>',
    controller: 'any controller'
})

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

代码语言:javascript
复制
$routeParams.hash

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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34971584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档