0

I have just recentely used AngularJS to "convert" a data structure I had in pure SVG format into JSON format.

Now, I want to store such a structure in a MongoDB database to start finally connecting some components of the MEAN stack together and start seeing some things working! Basically, I have the following code inside a Webstorm AngularJS project:

JS:

var app = angular.module('app', []);
var RectangleDim=30;

app.controller('MainCtrl', function($scope) {

    $scope.graph = {'width': 5000, 'height': 5000};

    $scope.circles = [

      /*  JSON.parse("{\"x\": 85, \"y\": 20, \"r\":15}"),

        {"x": 20, "y": 60, "r":20},

        {"x": 18, "y": 10, "r":40} */
    ];

        $scope.draw=function(val)
        {
           // val = document.getElementById("NumQuest").value;
            return JSON.parse('{\"cx\":'+val+', "cy": 20, "r":30}');
           // $scope.circles.push(JSON.parse('{\"x\":'+val+', "y": 220, "r":30}'));
        };

    $scope.rectangles = [

       //     {'x':220,  'y':220,  'width' : 300, 'height' : 100},
       // {'x':520,  'y':220,  'width' : 10, 'height' : 10},
    ];

        $scope.DrawRect=function(xpos,ypos) {
           return JSON.parse('{\"x\":' + xpos + ', \"y\":' + ypos + ', \"width\":' + RectangleDim + ', \"height\":' + RectangleDim+ '}');
        };


        $scope.Debug=function(desiredNo){
            desiredNo=document.getElementById("NumQuest").value;
            for(var i = 0;i < RectangleDim*desiredNo+desiredNo;i++){
                $scope.rectangles.push($scope.DrawRect(i+RectangleDim+1,40));
            }
        };

        $scope.DrawLineOdd=function(desiredNo,lineNo,pozY){
            var pozX = lineNo*RectangleDim;
            var aux = 2*Math.floor(Math.sqrt(desiredNo))-1-2*lineNo;
            for (var j = 0; j < aux; j++) {
                $scope.rectangles.push($scope.DrawRect(pozX, pozY));//$scope.DrawRect(pozX, pozY);
                pozX += RectangleDim;
            }
            //return aux;
        };

        $scope.DrawMatrixPerfectProgression=function(desiredNo) {

            desiredNo=document.getElementById("NumQuest").value;


            var line=0;
            var pozy=0;
            while(line<Math.floor(Math.sqrt(desiredNo))) {
                $scope.DrawLineOdd(desiredNo, line, pozy);
                //document.getElementById("val").innerHTML = teste;
                line += 1;
                pozy+=RectangleDim;
            }
            //document.getElementById('tablePrint').innerHTML = finalTable;
        };

        $scope.DrawLineEven=function(desiredNo, lineNo, pozY){
            var pozX = lineNo*RectangleDim;
            //var pozY = lineno*20;
            var aux = 2*Math.floor(Math.sqrt(desiredNo))-2*lineNo;
            for (var j = 0; j < aux; j++) {
                $scope.rectangles.push($scope.DrawRect(pozX, pozY));
                pozX += RectangleDim;
            }
            //return aux;
        };

        $scope.DrawMatrixEvenProgression=function(desiredNo) {

            desiredNo=document.getElementById("NumQuest").value;

            var line=0;
            var pozy=0;
            while(line<Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)) {
                $scope.DrawLineEven(desiredNo, line, pozy);
                //document.getElementById("val").innerHTML = teste;
                line += 1;
                pozy+=RectangleDim;
            }
            //document.getElementById('tablePrint').innerHTML = finalTable;
        };

    $scope.AddExtraRectangles=function(desiredNo) {
        desiredNo = document.getElementById("NumQuest").value;

        var arg1 = desiredNo - (  Math.floor(Math.sqrt(desiredNo))*Math.floor(Math.sqrt(desiredNo)));
        var arg2 = desiredNo-(Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)*Math.floor((Math.sqrt(4*desiredNo+1)-1)/2))-Math.floor((Math.sqrt(4*desiredNo+1)-1)/2);
        var OptimalLeftOver = Math.min( arg1  ,arg2 );
        //We add two rectangles per row: one at the beginning one at the end
        //we start with the row below the first one

        var line;
        var pozy;
        var pozx1, pozx2;
        var nRectLine_i;

        if(OptimalLeftOver===arg1){
            line=1;//1st line is skipped
            pozy=RectangleDim;
            pozx1 = 0;
            while(OptimalLeftOver>0) {
                nRectLine_i = 2* Math.floor(Math.sqrt(desiredNo))-1-2*line;
                pozx2 = (line-1)*RectangleDim+RectangleDim*(nRectLine_i+1);//pozx1+nRectLine_i+2*RectangleDim;
                $scope.rectangles.push($scope.DrawRect(pozx1,pozy));
                OptimalLeftOver-=1;
                if(OptimalLeftOver>0) {
                    $scope.rectangles.push($scope.DrawRect(pozx2, pozy));
                    OptimalLeftOver -= 1;
                }
                //document.getElementById("val").innerHTML = teste;
                line += 1;
                pozy+=RectangleDim;
                pozx1=RectangleDim*line - RectangleDim;
            }
            //document.getElementById('tablePrint').innerHTML = finalTable;
        }
        else {
            line=1;//1st line is skipped
            pozy=RectangleDim;
            pozx1 = 0;
            while(OptimalLeftOver>0) {
                nRectLine_i = 2* Math.floor(Math.sqrt(desiredNo))-2*line;
                pozx2 = RectangleDim*(line-1)+RectangleDim*(nRectLine_i+1);//pozx1+nRectLine_i+2*RectangleDim;
                $scope.rectangles.push($scope.DrawRect(pozx1,pozy));
                OptimalLeftOver-=1;
                if(OptimalLeftOver>0) {
                    $scope.rectangles.push($scope.DrawRect(pozx2, pozy));
                    OptimalLeftOver -= 1;
                }
                //document.getElementById("val").innerHTML = teste;
                line += 1;
                pozy+=RectangleDim;
                pozx1=RectangleDim*line - RectangleDim;
            }
            //document.getElementById('tablePrint').innerHTML = finalTable;
        }
    };

    /*    $scope.DrawMatrix=function(desiredNo)
        {
            /* Chooses optimal leftover number based on the progression formulas.
             Attempts to minimize the work of the designer of the response form without
             making too much assumptions

            desiredNo = document.getElementById("NumQuest").value;
            var arg1 = desiredNo - (  Math.floor(Math.sqrt(desiredNo))*Math.floor(Math.sqrt(desiredNo)));
            var arg2 = desiredNo - (Math.floor((Math.sqrt(4*desiredNo+1)-1)/2)*Math.floor((Math.sqrt(4*desiredNo+1)-1)/2))-Math.floor((Math.sqrt(4*desiredNo+1)-1)/2);
            var OptimalLeftOver = Math.min( arg1  ,arg2 );
            document.getElementById("val").innerHTML = 'There are '+OptimalLeftOver+' questions missing!'+ arg1+ '___'+arg2;
            console.log(arg1);
            if(OptimalLeftOver===arg1){
                DrawMatrixPerfectProgression(desiredNo);
                AddExtraRectangles(desiredNo);
            }
            else {
                DrawMatrixEvenProgression(desiredNo);
                AddExtraRectangles(desiredNo);
            }
        }; */
}
);

angular.bootstrap(document.getElementById('body'), ["app"]);

The relevant part of the code is the $scope.rectangles array which contains the JSON.parse of the strings representing my data structure on the html side and that structure in JSON (or JSON parsed or whatever) is what I want to save in the MongoDB database...How can I do that? The HTML relevant part is just like this:

HTML:

 <p><button ng-click="DrawMatrixEvenProgression(NumQuest)">Draw</button></p>

    <svg ng-attr-height="{{graph.height}}" ng-attr-width="{{graph.width}}">

     <rect ng-repeat="rect in rectangles"

           ng-attr-x="{{rect.x}}"

           ng-attr-y="{{rect.y}}"

           ng-attr-width="{{rect.width}}"

           ng-attr-height="{{rect.height}}">

     </rect>

     </svg>

Any help will be appreciated... Can I start by adding more files to that project to handle the database and then things will be linked together?

Like adding stuff to handle the mongoose and the connections?

Thanks in advance!

2
  • 1
    Perhaps you're missing N and E, possibly M too...? This tutorial might help. (Yes, you'll definitely need to add more "stuff" for the missing bits... :-)) Commented Aug 8, 2015 at 16:54
  • 1
    why are you using strings for data and then parsing them with JSON.parse? Makes more sense to use arrays and objects the same way you would receive them. Also should not have any DOM related code in a controller Commented Aug 8, 2015 at 16:57

1 Answer 1

1

Because Angular is a front-end framework. So to communicate with database (in this case MongoDB) you need to have application on the server-side to handle this and I suggest you to use Node.js and Mongoose as a MongoDB driver.

Node.js
Mongoose

Come back to Angular, you can create Angular service or factory and let the them talk to your server with service like $http or $resource.

Angular service documentation

Example for angular service

angular.module('app')
  .factory('RectangleService', function($http){
     return {
       create: create
     }

     function create(rectangle){
       // make http request to the server
       return $http({
         url: 'API_URL', 
         method: 'GET',
         params: rectangle
       });
     }
  });

After you create your service you have to inject it to your controller and you may create some function to your $scope to talk with service like this

app.controller('MainCtrl', function($scope, RectangleService) { // <-- Inject service to controller
  // your controller code

  $scope.createRectangle = function(rectangle){
    RectangleService.create(rectangle);
  }
});

You can map createRectangle function to directive like ng-click and pass your json data as a parameter

Because I don't know what server-side language you can use, so I don't come with an example for Node.js & Mongoose

Hope this can help :)

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

Comments

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.