如何根据AngularJS中的条件注入依赖项?

时间:2016-09-16 08:15:11

标签: javascript angularjs dependency-injection

我编写了一个控制器,用于AngularJS应用程序中不同部分的不同HTML模板。

例如,控制器以两种不同的方式被不同地调用:

  1. Way1:控制器在打开模态时被调用。现在$modalInstance 作为依赖项传递,在这种情况下不是undefined
  2. Way2:控制器在页面div中调用。现在$modalInstanceundefined,但仍然作为依赖项传递,因此我得到了这个错误 angular.js:11699 Error: [$injector:unpr] Unknown provider: $modalInstanceProvider <- $modalInstance <- MyController
  3. 我正在寻找一种方法来处理这个问题,只有在定义它时才注入依赖项$modalInstance

    示例代码:

    <!-- Common Controller -->
    <script type="text/javascript">
        angular.module('myApp')
        .controller('MyController', ['$scope',  '$modal', '$modalInstance', '$filter', 'sharedService', function ($scope, $modal, $modalInstance, $filter, sharedService) {
            /*Code required for to popup*/
            $scope.closeModal = function () {
               $modalInstance.dismiss('cancel');
            };
    
            /* Remaining code for the controller
             * This code is required for both popup, and other non-popup HTML divs
             */
        }]);         
    </script>
    
    <!-- modal HTML -->
    <div class="modal-container" ng-controller="MyController">
        <button ng-click="closeModal()">Close Modal</button>
        <div class="common-html">
            <!-- 
                ***************************
                *** remaining HTML code ***
                *************************** 
            -->
        </div>    
    </div>  
    
    <!-- non-modal elemenl HTML -->
    <div class="modal-container" ng-controller="MyController">
        <div class="common-html">
            <!-- 
                ***************************
                *** remaining HTML code ***
                *************************** 
            -->
        </div>
    </div> 
    

0 个答案:

没有答案