AngularJS : The correct way of binding to a service properties

前端 未结 10 1849
天命终不由人
天命终不由人 2020-11-28 00:30

I’m looking for the best practice of how to bind to a service property in AngularJS.

I have worked through multiple examples to understand how to bind to properties

10条回答
  •  半阙折子戏
    2020-11-28 00:47

    Late to the party, but for future Googlers - don't use the provided answer.

    JavaScript has a mechanism of passing objects by reference, while it only passes a shallow copy for values "numbers, strings etc".

    In above example, instead of binding attributes of a service, why don't we expose the service to the scope?

    $scope.hello = HelloService;
    

    This simple approach will make angular able to do two-way binding and all the magical things you need. Don't hack your controller with watchers or unneeded markup.

    And if you are worried about your view accidentally overwriting your service attributes, use defineProperty to make it readable, enumerable, configurable, or define getters and setters. You can gain lots of control by making your service more solid.

    Final tip: if you spend your time working on your controller more than your services then you are doing it wrong :(.

    In that particular demo code you supplied I would recommend you do:

     function TimerCtrl1($scope, Timer) {
       $scope.timer = Timer;
     }
    ///Inside view
    {{ timer.time_updated }}
    {{ timer.other_property }}
    etc...
    

    Edit:

    As I mentioned above, you can control the behaviour of your service attributes using defineProperty

    Example:

    // Lets expose a property named "propertyWithSetter" on our service
    // and hook a setter function that automatically saves new value to db !
    Object.defineProperty(self, 'propertyWithSetter', {
      get: function() { return self.data.variable; },
      set: function(newValue) { 
             self.data.variable = newValue; 
             // let's update the database too to reflect changes in data-model !
             self.updateDatabaseWithNewData(data);
           },
      enumerable: true,
      configurable: true
    });
    

    Now in our controller if we do

    $scope.hello = HelloService;
    $scope.hello.propertyWithSetter = 'NEW VALUE';
    

    our service will change the value of propertyWithSetter and also post the new value to database somehow!

    Or we can take any approach we want.

    Refer to the MDN documentation for defineProperty.

提交回复
热议问题