AngularJS, is this way of using service good?

后端 未结 3 1792
误落风尘
误落风尘 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:10

    AngularJS templates can only invoke functions that are available on a scope. So, whatever approach you take you need to have your function on a scope.

    If you want your service's functions to be directly invokable from a template you've got several options:

    The one you've tried - that is, expose the whole service on a scope:

    $scope.service = service;
    

    and then in a template:

    Hello {{service.getUsername();}}

    This is one-liner in a controller and makes all the service methods available on a scope and thus to templates.

    Expose methods one by one

    to have precise control over what gets exposed:

    $scope.getUsername = service.getUsername;
    

    and then in a template:

    Hello {{getUsername();}}

    This requires more work exposing methods but gives you fine-grained control over what gets exposed.

    Expose proxing methods:

    $scope.getMyUsername = function() {
       //pre/post processing if needed 
       return service.getUsername();
    };
    

    You can use any of those methods or mix and combine them but at the end of the day a function must end up on a scope (either directly or through another object exposed on a scope).

提交回复
热议问题