Search code examples
javascriptangularjsparse-platformparse-server

How to access Parse object properties in AngularJS?


I'm building out an AngularJS app that uses data from a parse-server backend. I retrieve any data through services, which can be called from my controllers. But due to how Parse objects work all properties are accessed through a get function, and my html becomes filled with lines like <p>{{myObject.get('title')}</p>}.

Ideally I would like to access properties just like a regular object e.g. myObject.title, but I can't seem to find a reference for best practices when using the Parse JS sdk with AngularJS.

My searches have turned up several people pointing to this example of Parse and AngularJS boilerplate by BRANDiD but links to their actual code and site seem to be dead.

Any insight into how this is best approached would be much appreciated!


Solution

  • I would create a service that would return a JSON converted parse response.

    (Pseudo) code:

    Service:

    app.service('Books', function($q) {
      return {
        findBookById: function(id) {
    
          var deferred = $q.defer();
    
          // parse query logics .. 
          var Book = Parse.Object.extend("Book");
          var query = new Parse.Query(Book);
          query.equalTo("book_id", id);
    
          query.first({
            success: function(response) {
              // convert to JSON so that you can access properties directly
              // eg. book.name (instead of book.get('name'))
              deferred.resolve(response.toJSON());
            },
            error: function(err) {
              deferred.reject(err);
            }
          });
          return deferred.promise;
        }
      };
    });
    

    Controller:

    app.controller('BookCtrl', function($scope, Books) {
      Books
        .findById(10)
        .then(function(book) {
          $scope.book = book;
        })
        .catch(function(err) {
          alert('Error occurred : ' + err.message);
        });
    });
    

    View:

    <p>Book Name: {{book.name}}</p>