0

This question might seem a bit strange. I'm trying to create functions to update the database via angular and because I'm lazy my function will be

gettable('tablebame')

It will select the table (MySQL) matching the parameter and return it. I didn't think about this issue untill I noticed it only worked with 1 table.

$scope.users = {};

var gettable = function(name) {

    httpFactory.setname(name);


    httpFactory.get(function(response) {

        $scope./* name inserted in function here */ = response;

    });

};

gettable("users");

I still had a static name where the comment is right now. I have tried things like but it doesn't work.

('$scope.' + name)

Is there any way to bind the return value 'response' to $scope. + 'name'?

Noel Heesen
  • 223
  • 1
  • 4
  • 14
  • 3
    `$scope[name] = response`? – Tony Oct 02 '15 at 22:03
  • SyntaxError: missing name after . operator – Noel Heesen Oct 02 '15 at 22:07
  • this seems like it would work if you use bracket syntax (`$scope[name]=response`), however you may want to take some time to really be sure this architecture makes sense in the long term. You don't want to be dealing with issues weeks or months from now because you were trying to cut corners in the beginning here. – Claies Oct 02 '15 at 22:08
  • you don't use a `.` operator at all if you use the bracket syntax... – Claies Oct 02 '15 at 22:08
  • choosing data to work with on your server based on a string can be troublesome, as you don't get syntax or type checking, and a misspelled name in one of your string parameters could result in an error that wouldn't be detected until runtime. – Claies Oct 02 '15 at 22:11
  • It works awesome! :) Thisi s the first time I'm connecting to a DB using it for a small website. I don't know any better way to get and store data so easy as this. 3 functions is all it will take to CRD this way. – Noel Heesen Oct 02 '15 at 22:17
  • Possible duplicate of [How do I add a property to a Javascript Object using a variable as the name?](http://stackoverflow.com/questions/695050/how-do-i-add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Tony Oct 02 '15 at 22:20

1 Answers1

1

Just use javascript's bracket syntax to access the property with a variable name. Since $scope itself is just an object you can use

httpFactory.get(function(response) {

    $scope[name] = response;

});
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53