amanuel2
amanuel2

Reputation: 4646

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.

Cloud9

Plunker

And here is 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"

EDIT 2

: Ok Now it works but im confused on how to use it on app.config.. i My provider is Hash:

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

And when it goes to the controller i set the hash and get the has ... 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:

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

What i was trying to say earlier was that i want to somehow configure the randomly generated Hash in my app.config() when statements. so in my app.config. WHEN the USER is in /RANDOMLYGENERATEDHASH have a template: '<h1>Test</h1>' . This is what i tried but dosent workk...

It is the fourth one on the .when() Statements..

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: '/'
      }); 
});

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

Ok This is my roomcontroller.js Now..: (Important detail at bottom of controller)

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

        });




    }
])

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

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

Upvotes: 11

Views: 792

Answers (1)

Alex Kopachov
Alex Kopachov

Reputation: 733

There are two problems in your code:

  1. Definition of "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. The correct "roomController" definition should be like this:

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. 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:

You defined 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). So your app.config declaration should be like this:

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:

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:

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:

.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. 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.

Upvotes: 4

Related Questions