我是 AngularJS 新手,之前有过 WPF MVVM 经验。现在,我对 $scope 感到非常困惑,它看起来像是一个 View 模型,我们可以在上面定义函数并使用 ng-change、ng-click 或其他一些 Angular Directive(指令)来连接函数。但如果函数与 UI 无关,我们是否也应该将它们附加到 $scope 上?我们应该在 $scope 上定义什么类型的函数?我还阅读了一些文章,建议使用服务来封装真正的实现,并在 $scope 的方法中调用服务,这可以解耦一些 http 调用。但我认为它会创建太多的服务,并且有些服务不会被重用。有什么想法吗?
最佳答案
在 $scope 中,您可以绑定(bind)方法和字段,这些方法和字段应该可以使用 $scope.$eval() 或 $scope.$apply() 来使用(这些方法在您使用插值时使用隐式: {{itIsInterpolation}} 或 ng- 前缀html 代码中的属性)。 所以你可以考虑 $scope 方法,例如: 这些方法可以从 HTML 层调用,仅此而已。
但是根据 MVC 思想,您使用 Controller 只是为了要求服务层执行一些逻辑操作,然后返回(渲染并放入 $scope 中)一些结果。这里也一样。例如:
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;
});
}
}
关于javascript - $scope 应该附加什么方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540886/