如何制定一个在特定控制器中调用函数的角度指令

时间:2014-01-21 21:29:06

标签: javascript angularjs

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

我有一个根控制器包含我的应用程序的每一页......

<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');
    };

}]);

1 个答案:

答案 0 :(得分:2)

我建议你从你的指令向rootScope广播一个事件,并为你的控制器添加一个触发模态的监听器,如:

//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
});
相关问题