javascript - 如何制定在特定 Controller 中调用函数的 Angular 指令

标签 javascript angularjs

产品图像出现在我的应用程序的许多页面中,我想设计一个指令,以便在访问者单击任何产品图像时显示模态框,无论它位于我的应用程序中的哪个位置。

我有一个根 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/

相关文章:

javascript - window.onbeforeunload 在 Android Chrome 上不会触发 [alt.解决方案?]

javascript - Angular 2,自定义组件的类属性

javascript - MuiThemeProvider.render() : A valid React element (or null) must be returned

Javascript - 查找对象的容器

javascript - 如何折叠 Firefox 中 JSON View 中的所有对象

javascript - 动态添加项目到ng-repeat数组javascript

angularjs - 在全新的 ubuntu 安装中使用 NPM 安装 angular-cli 时出错

javascript - Rails - 找不到 JavaScript 运行时?

javascript - Protractor 排序基本测试。登录后运行测试

javascript - Angular 指令 ng-model 适用于数组,但不适用于字符串