产品图像出现在我的应用程序的许多页面中,我想设计一个指令,以便在访问者单击任何产品图像时显示模态框,无论它位于我的应用程序中的哪个位置。
我有一个根 Controller 包含我的应用程序的每一页......
<section class="container" ng-controller="RootController">
// Header
// Body
// Footer
</section>
我想在我的 RootController 中放置一个 showProductModal()
函数,并在我的指令中调用它。
最后,我想将一个对象参数传递到 showProductModal(product)
函数中,以便我可以在 RootController 范围内的其他地方使用它...
这是我开始的内容,只是一些入门代码...
// HTML
<img src="path/to/product/image.jpg" product>
// Directive - Product Modal
app.directive("product", function() {
return {
restrict: "A",
replace: true,
controller: 'RootController',
link: function(){
};
};
});
// Root Controller
angular.module('app').controller('RootController', ['$scope', function ($scope) {
$scope.showProductPopup = function(item) {
$scope.product = item;
$('#productModal').modal('show');
};
}]);
最佳答案
我建议您从指令向 rootScope 广播一个事件,并向 Controller 添加一个监听器来触发模式,例如:
//directive
controller: function($scope, $rootScope){
$scope.onClick = function(){
$rootScope.$broadcast('openModal', someObjectToPopulateModal);
}
}
//main controller
$scope.$on('openModal', function(e, someObjectToPopulateModal){
//do something with the object you sent from the directive
//and trigger the function that opens your modal
});
关于javascript - 如何制定在特定 Controller 中调用函数的 Angular 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21269475/