AngularJS, is this way of using service good?

后端 未结 3 1794
误落风尘
误落风尘 2020-12-13 01:05

i\'ve this HTML:

Hello {{name}}

and the controller is:

function myCtrl(scope, service) {
    scope.name          


        
3条回答
  •  伪装坚强ぢ
    2020-12-13 01:25

    Another way to expose your service within your $scope would be to add a function pointer to your service method/data object.

    scope.serviceData = service.data;
    // Or
    scope.getServiceData = service.getData;
    

    Within your view you can then invoke it by using parentheses.

    
    // Or
    
    // Or
    {{getServiceData().key}}
    

    I personally like this approach and i am currently using it in order to keep multiple views in sync with the same data. It does bring up some issues though as explained here: AngularJS. Best practice concerning proper two way data binding from a service

    As to exposing to much data i am currently trying to do something like this.

    // Within your view.
    {{getServiceDataByKey('key')}}
    
    // In your controller.
    scope.getServiceDataByKey = service.getServiceDataByKey;
    
    // In your service.
    getServiceDataByKey : function (key) {
       return dataObject[key];
    }
    

    The reason why i am doing this is that we want to keep the controllers as clean as possible and have all our data in one centralized place. Also most data within the service should be exposed.

提交回复
热议问题