0

I'm building a role based login for an angular app and when you first enter your credentials a session object is sent back with a bunch of properties, including an array of roles the user can select to sign in as. When the user selects the radio button for the corresponding role they want to be signed in as, e.g. "Administrator", I use ng-model' to update$scope.model.selected` to whatever object they chose.

However, at some point in the UI $scope.model gets parsed into a string when I need it to be a javascript object. In short, I'm trying to convert my model back to an object and I can't get JSON.parse($scope.model) to work.

Here's my controller:

$scope.submit = function() {
      $http
        .post(app.api.root + 'session-tokens', $scope.user)
        .then(
          // SUCCESS
          function (response) {
            $scope.model = { selected: response.data.results.roles[0] };
            $scope.results = response.data.results;
            $scope.isCorrect = true;
            $scope.welcome = 'Welcome, ' + $scope.user.username + '!';

            // redirect after login -- need to change this to a profile page
            // $location.path('/patients/22');
            $scope.login = function() {
              $scope.model = JSON.parse($scope.model);
              authSvc.user({
                id: response.data.results.userId,
                token: $scope.model.selected.token,
                role: $scope.model.selected.roleName,
                providerName: $scope.model.selected.providerName,
                username: $scope.user.username,
                isAuthenticated: true
              });
              $scope.user = authSvc.user();
              console.log(typeof $scope.model.selected);
            };
          }
};

The function that I want to do the conversion is $scope.login(), which fires after the user selects a role and clicks login.

Any idea how I can get this to work? And I don't think I'm on a new enough version of angular to use angular.fromJson.

Thanks.

EDIT

Here's the error I get in the console:

SyntaxError: Unexpected token o
at Object.parse (native)
at Scope.$scope.login (eval at <anonymous> (http://localhost:4000/$js/jquery.js:336:5), <anonymous>:32:39)
at http://localhost:4000/$js/angular.js:10288:21
at http://localhost:4000/$js/angular.js:18086:17
at Scope.$eval (http://localhost:4000/$js/angular.js:12045:28)
at Scope.$apply (http://localhost:4000/$js/angular.js:12145:23)
at Scope.$delegate.__proto__.$apply (<anonymous>:855:30)
at HTMLFormElement.<anonymous> (http://localhost:4000/$js/angular.js:18085:21)
at HTMLFormElement.jQuery.event.dispatch (http://localhost:4000/$js/jquery.js:4371:9)
at HTMLFormElement.elemData.handle (http://localhost:4000/$js/jquery.js:4057:28) 

EDIT

So $scope.model does actually return an object, but $scope.model.selected returns a json string, and I need it to be an object.

The string returned is:

{"roleName":"Group Provider","providerId":100,"providerName":"TestProvider","token":"XXX"}

CONSOLE.LOGS

console.log(response.data.results):
Object {userId: 3, roles: Array[2]}

console.log(response.data.results.roles[0]):
Object {roleName: "Administrator", providerId: 2, providerName: "TestLastNAme, Test", token: "xxx", $$hashKey: "0fL"}

console.log($scope.model):
Object {selected: "{"roleName":"Group Provider","providerId…Nn0.lwB6AggcMkvH_LcQzpUdLlbk3XBHTGBqCd8K07HBIfo"}"}

console.log($scope.model.selected):
{"roleName":"Group Provider","providerId":237,"providerName":"TestProvider","token":"xxx"} 

console.dir($scope.model):
Object
    selected: "{"roleName":"Insurance Group Provider","providerId":237,"providerName":"TestProvider","token":"xxx"}"
    __proto__: Object
6
  • What is the text of $scope.model? (My guess: an error message.) Commented Jun 26, 2014 at 23:28
  • I added another edit. Commented Jun 26, 2014 at 23:37
  • What is the exact json string? Commented Jun 26, 2014 at 23:38
  • That error occurs when you attempt to use JSON.parse() on an object. Are you sure you need to be using JSON.parse() at all? Commented Jun 26, 2014 at 23:40
  • I added the string. Yes...I need the properties from the string I added above in object form. Commented Jun 26, 2014 at 23:41

2 Answers 2

1

That error occurs when you attempt to use JSON.parse() on an object.

Sign up to request clarification or add additional context in comments.

4 Comments

The problem is that somehow it's getting converted to a string when the vaue changes in the view. When I initially set $scope.model it is an object, so I dont need to parse that; I need to parse the new model being saved in its place.
console.log(response.data.results); and console.log(response.data.results.roles[0]); and console.log($scope.model); and console.log($scope.model.selected);
you're definitely trying to use JSON.parse() on an object. we can figure out why with some logging.
sorry, try console.dir($scope.model); for me as well.
1

All of that and it turns out the problem was I was using value="{{model}}" on the radio buttons instead of angular's ng-value="model". value= will parse the object into a string while ng-value will keep it as an object.

1 Comment

To clarify, that's because the result of {{ }} is the evaluation of the expression within, no matter where you use it. In your case that would result in a string containing the contents of the variable model. Good job finding the solution! If we had seen your HTML it would've been obvious, but hindsight is 20/20.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.