AngularJS : The correct way of binding to a service properties

前端 未结 10 1846
天命终不由人
天命终不由人 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 01:00

    From my perspective, $watch would be the best practice way.

    You can actually simplify your example a bit:

    function TimerCtrl1($scope, Timer) {
      $scope.$watch( function () { return Timer.data; }, function (data) {
        $scope.lastUpdated = data.lastUpdated;
        $scope.calls = data.calls;
      }, true);
    }
    

    That's all you need.

    Since the properties are updated simultaneously, you only need one watch. Also, since they come from a single, rather small object, I changed it to just watch the Timer.data property. The last parameter passed to $watch tells it to check for deep equality rather than just ensuring that the reference is the same.


    To provide a little context, the reason I would prefer this method to placing the service value directly on the scope is to ensure proper separation of concerns. Your view shouldn't need to know anything about your services in order to operate. The job of the controller is to glue everything together; its job is to get the data from your services and process them in whatever way necessary and then to provide your view with whatever specifics it needs. But I don't think its job is to just pass the service right along to the view. Otherwise, what's the controller even doing there? The AngularJS developers followed the same reasoning when they chose not to include any "logic" in the templates (e.g. if statements).

    To be fair, there are probably multiple perspectives here and I look forward to other answers.

提交回复
热议问题