如何从AngularJS模板中调用服务或工厂?

时间:2022-09-24 23:13:24

I have HTML code with variable:

我有变量的HTML代码:

<span>{{category}}</span>

Also I have service CategoryService with method get() that returns me string name of category. How I can use this method in template like as:

此外,我有使用方法get()的服务CategoryService,它返回类别的字符串名称。我如何在模板中使用此方法,如:

<span>{{category | CategoryService.get}}</span>

2 个解决方案

#1


2  

Controllers connect the model and the view. You'll want a function in your controller that, in turn, calls the service:

控制器连接模型和视图。您需要控制器中的一个功能,然后调用该服务:

$scope.getCategory = function(CategoryService) {
    var cat = CategoryService.get();
    return cat;
});

Then you'd call that function from your view:

然后你从你的视图中调用该函数:

<span>{{getCategory()}}</span>

#2


2  

I usually create a controller for the web page:

我通常为网页创建一个控制器:

<div ng-controller="OneCtrl">
<span>{{category }}</span>
</div>

And inside the controller I call the service:

在控制器内我调用服务:

myApp.controller("OneCtrl", ['$scope', '$location','$window', 'CategoryService',
  function($scope, $location,$window, CategoryService) {

    $scope.category = CategoryService.get();

  }
]);

#1


2  

Controllers connect the model and the view. You'll want a function in your controller that, in turn, calls the service:

控制器连接模型和视图。您需要控制器中的一个功能,然后调用该服务:

$scope.getCategory = function(CategoryService) {
    var cat = CategoryService.get();
    return cat;
});

Then you'd call that function from your view:

然后你从你的视图中调用该函数:

<span>{{getCategory()}}</span>

#2


2  

I usually create a controller for the web page:

我通常为网页创建一个控制器:

<div ng-controller="OneCtrl">
<span>{{category }}</span>
</div>

And inside the controller I call the service:

在控制器内我调用服务:

myApp.controller("OneCtrl", ['$scope', '$location','$window', 'CategoryService',
  function($scope, $location,$window, CategoryService) {

    $scope.category = CategoryService.get();

  }
]);