1
confirm("Ohhh, hello there, is it Ok to click Cancel?");

I think that this is, basically, a question about CRUD on Angular. I'm kind of confused about getters and setters, mainly because Angular do almost all the job in getting and setting things because of its two way data binding. I want to know what's the best scalable way to create getters and setters so I wont need to modify my functions in the future.

On the first Arrangement, I'm trying to be as simple as I can be, but I feel uncomfortable in getting and getting to set.

Arrangement 01:

$scope.getData = function(){
  $http.get(url + '/data')
  .then( function (res) {
    return res.data; } );
};

$scope.setData = function () {
  $scope.data = $scope.getData();
};

$scope.insertData = function (data) {
  $http.post(url + '/data', { data: data})
  .then( function (res) {
    // nothing here. } );
};

On this second Arrangement, however, I'm trying to go directly where I need to. When I fetch data from the server, I'm automagicaly setting my $scope.data to the retrieved data;

Arrangement 02:

$scope.getData = function () {
  $http.get(url + '/data')
  .then( function (res) {
    $scope.data = res.data;
  });
};

$scope.insertData = function (data) {
  $http.post( url + '/data', { data: data })
  .then( function (res) {
    $scope.getData(); //To update.
    //OR $scope.data.push(res.data);
  });
};

Looking further, I've found this on the Angular Docs, but what's the point in using a getter/setter if Angular already do it? Looking into other technologies, it's hard to compare, because Angular has auto-get.

I don't even know how to formulate this question. But, basically, I want to know how could my getters and setters harm my future application and if there's a good way and why to create getters and setters in Angular.

Thanks for any advice.

Community
  • 1
  • 1
Rodmentou
  • 1,610
  • 3
  • 21
  • 39

3 Answers3

2

You good practice is to wrap your logic into Service. You have to know that in Angular, all services are Singleton, there is only a single instance of a Service.

I've made a simple example, by using $q.defer() which is the promise manager from the deferred API.

$q.defer() get 2 methods :

  • resolve(value) : which resolve our associated promise, by giving her the final value

  • reject(reason) : which resolve an promise error.

Controller

(function(){

function Controller($scope, $q, Service) {

  //Use promise manager
  var defer = $q.defer();
  ///Create our promise
  var promise = defer.promise;

  $scope.data = [];

  var newData = [
    {
      name:'john',
      age: 25
    },
    {
      name: 'toto',
      age: 13
    }
  ];

  Service.get().then(function(data){
    //Retrieve our data
    $scope.data = data;

    //Set new data to our factory
    Service.set(newData);

    //Retrieve new data
    Service.get().then(function(data){
      //Resolve new data
      defer.resolve(data);
    });

  });

  //Retrieve new dataset
  promise.then(function(data){
    $scope.data = data;
  })




}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

Service

(function(){

  function Service($q){

    var data = [0,1,2,3,4];

    function set(value){
      data = value;
    }

    function get(){
      return $q(function(resolve){
        //Simulate latency
        setTimeout(function(){
          //Resolve our data
          resolve(data);
        }, 1000);
      });
    }

    return {
      get: get,
      set: set
    };

  }

  angular
    .module('app')
    .factory('Service', Service);

})();

HTML

  <body ng-app='app' ng-controller="ctrl">

    <pre>{{data}}</pre>

  </body>

So, you can set some data by using the service, and retrieve it when you want. Don't forget that service is singleton.

You can see the Working Plunker

Paul Boutes
  • 3,285
  • 2
  • 19
  • 22
  • Thank you, @Paul Boutes, you've shown the technical aspects. I'll strength my studies on promises and services so I can better understand your code. But, in the theoretical way, you helped me a lot. Thanks! – Rodmentou Aug 27 '15 at 20:21
1

In JavaScript you typcially don't use getters and setters like in OOP languages, especially because you do not have a notion of privateness (so anyone can access your fields). ES5 has getters and setters, but it also adds this missing capabilities of hiding implementation details. In case you want getters and setters for additional logic in your AngularJS app, you could simply define additional fields which are updated using $watch.

Furthermore you solution with sending an HTTP request on every change is a it of an overhead if you do this per field. What you instead to is writing directly to fields.

While e.g. WPF/C# requires you to define setters to raise OnPropertyChanged, you don't need this in AngularJS. Everything that you write in AngularJS will automatically trigger a so-called $digest cycle, where it checks for changes that have been made. It will then automagically update your user interface, give that you use template bindings or ng-model directives.

Netzdoktor
  • 526
  • 4
  • 15
  • In the application, I'm 'getting' and 'setting' every template change and after every change that needs the DOM to be updated. So, @Darneas , I should forgot the OOP and focus on the Event orienteds? – Rodmentou Aug 27 '15 at 19:38
  • @RodrigoSouza: I updated my answer. You should do away with OOP in JavaScript. Not that it breaks things, but you add complexity without getting anything from it. All benefits of doing getters and setters in OOP are not present in JavaScript, so everything that remains is very complex code for simple tasks ;-). – Netzdoktor Aug 27 '15 at 19:43
  • This made me feel better. A friend of mine looked at my code and said 'why aren't you using getters and setters?', I said 'Well, it's too complex', but then he talked about complexity and scalability. So, I can use my getters to fetch data from the server and bind it to the local Scope objects without doing any bad thing to my maintainability of code? – Rodmentou Aug 27 '15 at 19:49
  • Now you are getting to a esoteric question. Maintainable code is code, which is well understood and can adapt easily to changing demands. AngularJS might at the beginning look very magic to you, but this is normal. Adding artifical complexity to it, in order to "make it understandable" helps nothing. A reader has to learn Angular and should cope with that. And for these advanced Angular developers, getter and setters are only unnecessary complexity.. – Netzdoktor Aug 27 '15 at 19:56
  • You made your point pretty solid, @Darneas. And I do like it! "A reader has to learn Angular and should cope with that", I loved this! Thank you a lot. – Rodmentou Aug 27 '15 at 20:02
1

If you think like pure Javascript, is basic the same logic, what angular does is create modules for you to use the best practice, so it is easy to use them.

function DataService($http) {
  this.get = function() {
    return $http.get(...);
  }

  this.create = function(newData) {
    return $http.post(...);
  }

  ..
}

and using angular, like Ali Gajani sayd, you basically can do this,

angular.module('myApp').service('DataService', ['$http', DataService]);

or with a factory style

function DataService($http) {
  var myPrivateVariable = "something";

  function get() {
    return $http.get(...);
  }
  ...

  // expose them public
  return {
    get: get
  };
}


angular.module('myApp').factory('DataService', ['$http', DataService]);
Guilherme
  • 1,980
  • 22
  • 23