2

I am attempting to define a variable conn in my controller.js.

With the code at the bottom, I get lots of horrible UI glitches, so I'm presuming the code below is wrong. If I try:

var conn;
conn.name = 'Fred';

I get what looks like a NullPointer Error "Cannot set property 'name' of undefined" when I attempt to set conn.name.

How do I define my variable?

var addDBConnControllerBase = app.controller('addDBConnControllerBase',
function($scope,$http,serviceFactory,$modal,$location,$log)
{
    $scope.saveDBConn = function()
    {
        var conn = {
            name,
            driverType,
            connectionString,
            userID,
            password
        };
        conn.name = $scope.addDBConnController.displayName;
        conn.driverType = $scope.addDBConnController.driverType;
        conn.connectionString = $scope.addDBConnController.connectionString;
        conn.userID = $scope.addDBConnController.userID;
        conn.password = $scope.addDBConnController.password;
        $log.debug('Saving db conn');
        $log.debug(JSON.stringify(conn));
    }
});
3
  • I would use a service for saving connection settings. It's more "angular-way" Commented Apr 9, 2015 at 10:42
  • Using a service is the second part of my task. This is angular day 1 for me and I was just making sure I could get the data from the screen to the controller to start with. :-) Commented Apr 9, 2015 at 10:56
  • [] is an array. {} is an object. Commented Apr 9, 2015 at 11:05

3 Answers 3

4
var newAttrs = {};
newAttrs[nameOfProp] = valueOfProp;

try this!!!

In your case I think this would be

var conn = {};
conn["name"] = 'Fred';
Sign up to request clarification or add additional context in comments.

Comments

4

You need to brush up on your javascript pronto! This:

var conn;

is a variable declaration, not definition. conn is still undefined after this statement so you can't go conn.name = .... You have to initialize things before you use them:

var conn = {};
conn.name = ...

or

var conn = {
  name: ...
};

Comments

-1

You should define variable conn as an array first. Like following.

var conn = [];
conn.name=$scope.addDBConnController.displayName;

3 Comments

Eeeeerrr, [] is not how you initialize objects.
I don't need an array. But thanks anyway. I learned something new :-)
[] is an array, {} is an object.

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.