AngularJS : The correct way of binding to a service properties

前端 未结 10 1826
天命终不由人
天命终不由人 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条回答
  •  -上瘾入骨i
    2020-11-28 01:02

    I think this question has a contextual component.

    If you're simply pulling data from a service & radiating that information to it's view, I think binding directly to the service property is just fine. I don't want to write a lot of boilerplate code to simply map service properties to model properties to consume in my view.

    Further, performance in angular is based on two things. The first is how many bindings are on a page. The second is how expensive getter functions are. Misko talks about this here

    If you need to perform instance specific logic on the service data (as opposed to data massaging applied within the service itself), and the outcome of this impacts the data model exposed to the view, then I would say a $watcher is appropriate, as long as the function isn't terribly expensive. In the case of an expensive function, I would suggest caching the results in a local (to controller) variable, performing your complex operations outside of the $watcher function, and then binding your scope to the result of that.

    As a caveat, you shouldn't be hanging any properties directly off your $scope. The $scope variable is NOT your model. It has references to your model.

    In my mind, "best practice" for simply radiating information from service down to view:

    function TimerCtrl1($scope, Timer) {
      $scope.model = {timerData: Timer.data};
    };
    

    And then your view would contain {{model.timerData.lastupdated}}.

提交回复
热议问题