Reputation: 2184
I am new to AngularJS, and have WPF MVVM experience before. Now, I'm very confused with $scope, it looks like it is a viewmodel, we can define functions on it and use ng-change, ng-click or some other angular directives to connect the functions. But if the function is not related to UI, should we also attach them to $scope? What types of functions should we define on $scope? I also read some articles which suggest using services to encapsulate the real implementation and just call the service in $scope's methods, this can decoupling some http call. But I think it will created too much services, and some of the services will not be reused. Any ideas?
Upvotes: 0
Views: 50
Reputation: 66
In $scope you bind methods and fields those should be available using $scope.$eval() or $scope.$apply() (those methods using implicity when you use interpolation: {{itIsInterpolation}} or ng- prefixed attributes in your html code). So you can think about $scope methods, like: Methods those can be invoked from the HTML layer and nothing more.
But by MVC ideology you using controller just to ask service layer to perform some logical action and then return (render and put into $scope) some result. Here the same. For example:
angular
.module('myApp', [])
.factory('ItemService', ItemService)
.controller('ItemController', ItemController);
function ItemService($http) {
return {
getAllItemCost: getAllItemCost
};
function getAllItemCost() {
return $http.get('api/items)
.then(function (response) {
var items = response.data;
return items.map(item => item.price).reduce((a, b) => a + b);
});
}
}
function ItemController(ItemService) {
$scope.itemsCost = 0;
$scope.updateItemsCost = function () {
ItemService.getAllItemCost()
.then(function (cost) {
$scope.itemsCost = cost;
});
}
}
Upvotes: 1
Reputation: 2110
Using services and factories is always a good idea for de-coupling codes. Don't worry about having two many services. You can do following --
1- Create a service for handling rest calls. Any rest call will use this service. The service will take common inputs like data, url, method etc and will be common for all controllers and services across your app.
2- Create factories as utility purpose. You can put some calculations and return proper data to controllers
3- Use constants for storing global variables so any change to such variables can be done at a single place.
4- Some services will be specfic to the custom directives and will not be used for any other purpose.
5- Scope can have functions which is accessed by your html. Other functions can be private to that controller.
Upvotes: 1