我是 angularjs 的新手,所以我有一个问题要问你。 在我的“标准 html 模板”中,我有一些用于购物车摘要的 html,该 html 位于所有页面上(就像快速管理购物车的弹出窗口)。所以我想使用共享 Controller 来处理常见的 html 片段,例如:
app.controller ('SharedCtrl', function ($ brooms, cartService) {
...
$ scope.cart = myBagService.get(); // get items from local store
$scope.removeCartItem = function(key){
myBagService.remove(key){..}; //remove stored item
myBagService.add(item){..}; //store item
$scope.cart = myBag.get(); //update binding items
}
...
}
这是完成此任务的正确方法吗? 如果是,我如何从其他 Controller 调用上述方法?例如在产品详细信息页面上我必须调用 add 方法。
最佳答案
是的,您可以通过使用 Angular 服务轻松共享函数/通用代码,但我认为共享函数/通用代码只是您问题的一半,正如您指出的,您需要共享“通用 html 片段”,因此为什么不使用指令
:
(function () {
'use strict';
app.directive('shoppingCart', function () {
return {
restrict: 'E',
controller: 'ShoppingCartController as vm',
template: function (element, attrs) {
return '<div data-ng-click="vm.onViewShpooingCart()">Click here to view shopping cart</div>';
}
};
});
})();
购物车指令的 Controller :
(function () {
'use strict';
app.controller('ShoppingCartController', ['$scope', 'sharedService'], function ($scope, sharedService) {
var self = this;
self.onViewShpooingCart = function () {
sharedService.fetchShppingCart();
};
});
})();
共享服务:
(function () {
'use strict';
app.services.factory('sharedService', [function () {
var service = {
fetchShppingCart: fetchShppingCart
};
return service;
function fetchShppingCart() {
//code to fetch shopping cart
}
}]);
})();
通过这样做,您最终不会在每个页面上重复购物车 html,它全部通过指令呈现,然后您可以使用如下指令:
<shopping-cart></shopping-cart>
关于javascript - 使用共享 Controller 来处理常见的 html 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31785640/