2015-05-22 6 views
0

У меня есть директива, которая работает правильно, когда закодированный таким образом:Разделительный Контроллер в Angularjs пользовательской директивы

return { 
      restrict: 'E', 
      transclude: true, //transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside. So we can access the vm calling this. 
      scope: { // As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in. 
       priceinformation: '=priceinformation' 
      }, 
      controller: ['$scope','PriceCalculatorService', '$state', function ($scope,PriceCalculatorService, $state) { 
       var controller={ 
        _$state:$state, 
        pricinginfo: [], 
        }; 
       //console.log(PriceCalculatorService); 
       //debugger; 
       PriceCalculatorService.getPricingInfo() 
        .success(function (result) { 
         controller.pricinginfo = result; 
        }) 
        .error(_handleError); 

       function _handleError(error) { 
        controller.error = error; 
        controller._$state.go('error-404'); 
       } 
       $scope.controller = controller; 
       return controller; 

      }], 
      templateUrl: 'app/common/directives/views/price-calculator.html', 

Однако я хочу, чтобы изолировать контроллер, и сделать это таким образом, вместо:

(function (app) { 

    'use strict'; 

    // @see https://docs.angularjs.org/guide/directive 
    // @important: Requires an object named pricinginformation is pushed into the directive. 
    var PriceCalculatorControl = (function() { 
     // scope is an isolated part of $scope limited this control only so we don't put a $ 
     var PriceCalculatorControl = ['scope','PriceCalculatorService', function PriceCalculatorControl(scope,PriceCalculatorService) { 
      var control = { 
       total: 0, 
       subscriptionUnitprice: 100, 
       totalcal: function totalcal() { 
        if (scope.priceinformation.subscriptioninfo.type == 'Daily') { 
         control.subscriptionUnitprice = 100; 
        } 
        else if (scope.priceinformation.subscriptioninfo.type == 'Monthly') { 
         control.subscriptionUnitprice = 500; 
        } 
        else { 
         control.subscriptionUnitprice = 100; 
        } 
        control.total = control.subscriptionUnitprice * scope.priceinformation.subscriptioninfo.period * scope.priceinformation.subscriptioninfo.subjectsselected; 
       } 
      }; 


      //kicking off the service 
      PriceCalculatorService.getPricingInfo() 
        .success(function (result) { 
         controller.pricinginfo = result; 
        }) 
        .error(_handleError); 

       function _handleError(error) { 
        controller.error = error; 
        controller._$state.go('error-404'); 
       } 

      // bootstrap 


      /* When injecting stuff, clean them up here. Like a timer that's running needs to be stopped. 
      element.on('$destroy', function() {});*/ 
      //register on scope 
       scope.PriceCalculatorControl.PriceCalculatorControl; 
     }]; 
     PriceCalculatorControl[2](); 

     return { 
      restrict: 'E', 
      transclude: true, //transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside. So we can access the vm calling this. 
      scope: { // As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in. 
       priceinformation: '=priceinformation' 
      }, 
      //controller: ['$scope','PriceCalculatorService', '$state', function ($scope,PriceCalculatorService, $state) { 
      // var controller={ 
      //  _$state:$state, 
      //  pricinginfo: [], 
      //  }; 
      // //console.log(PriceCalculatorService); 
      // //debugger; 
      // PriceCalculatorService.getPricingInfo() 
      //  .success(function (result) { 
      //   controller.pricinginfo = result; 
      //  }) 
      //  .error(_handleError); 

      // function _handleError(error) { 
      //  controller.error = error; 
      //  controller._$state.go('error-404'); 
      // } 
      // $scope.controller = controller; 
      // return controller; 

      //}], 
      templateUrl: 'app/common/directives/views/price-calculator.html', 
      link: PriceCalculatorControl 
     }; 
    }); 

    // Register the directive 

    app.directive('priceCalculator', PriceCalculatorControl); 

})(angular.module('app.common')); 

Этот второй метод не работает. scope.PriceCalculatorControl.PriceCalculatorControl; говорит, что PriceCalculatorControl не определен. PriceCalculatorService.getPricingInfo() говорит, что getPricingInfo не определен. Примечание: служба работает правильно. Я предполагаю, что проблема связана с инъекцией зависимостей, но не может понять, что. Пожалуйста, просветите меня. Спасибо.

+0

Отформатируйте ваш вопрос. Некоторые из вашего кода не помечены как код, что делает ваш вопрос нечитаемым – Michelangelo

+0

@Mikey Я отредактировал, спасибо. Обратите внимание, что для первой части я вставил только соответствующую часть, которая прокомментирована во второй части –

+0

Нет проблем. Просто быстрый совет: если вы хотите закомментировать блок сценария, вы можете поместить его между/* * /, экономит ваше время :) – Michelangelo

ответ

0

Попробуйте это:

(function (app) { 

    'use strict'; 

    // @see https://docs.angularjs.org/guide/directive 
    // @important: Requires an object named pricinginformation is pushed into the directive. 
    var PriceCalculatorControl = (['PriceCalculatorService', function (PriceCalculatorService) { 
     // scope is an isolated part of $scope limited this control only so we don't put a $ 
     var PriceCalculatorControl = function PriceCalculatorControl(scope) { 
      var control = { 
       total: 0, 
       subscriptionUnitprice: 100, 
       totalcal: function totalcal() { 
        if (scope.priceinformation.subscriptioninfo.type == 'Daily') { 
         control.subscriptionUnitprice = 100; 
        } 
        else if (scope.priceinformation.subscriptioninfo.type == 'Monthly') { 
         control.subscriptionUnitprice = 500; 
        } 
        else { 
         control.subscriptionUnitprice = 100; 
        } 
        control.total = control.subscriptionUnitprice * scope.priceinformation.subscriptioninfo.period * scope.priceinformation.subscriptioninfo.subjectsselected; 
       } 
      }; 


      //kicking off the service 
      PriceCalculatorService.getPricingInfo() 
        .success(function (result) { 
         controller.pricinginfo = result; 
        }) 
        .error(_handleError); 

      function _handleError(error) { 
       controller.error = error; 
       controller._$state.go('error-404'); 
      } 

      // bootstrap 


      /* When injecting stuff, clean them up here. Like a timer that's running needs to be stopped. 
      element.on('$destroy', function() {});*/ 
      //register on scope 
      scope.PriceCalculatorControl.PriceCalculatorControl; 
     }; 
     //PriceCalculatorControl[2](); 

     return { 
      restrict: 'E', 
      transclude: true, //transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside. So we can access the vm calling this. 
      scope: { // As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in. 
       priceinformation: '=priceinformation' 
      }, 
      //controller: ['$scope','PriceCalculatorService', '$state', function ($scope,PriceCalculatorService, $state) { 
      // var controller={ 
      //  _$state:$state, 
      //  pricinginfo: [], 
      //  }; 
      // //console.log(PriceCalculatorService); 
      // //debugger; 
      // PriceCalculatorService.getPricingInfo() 
      //  .success(function (result) { 
      //   controller.pricinginfo = result; 
      //  }) 
      //  .error(_handleError); 

      // function _handleError(error) { 
      //  controller.error = error; 
      //  controller._$state.go('error-404'); 
      // } 
      // $scope.controller = controller; 
      // return controller; 

      //}], 
      templateUrl: 'app/common/directives/views/price-calculator.html', 
      link: PriceCalculatorControl 
     }; 
    }]); 

    // Register the directive 

    app.directive('priceCalculator', PriceCalculatorControl); 

})(angular.module('app.common')); 

Кроме того, я не уверен, что это, как предполагается достичь:

PriceCalculatorControl[2](); 
+0

Это сработало хорошо. Хотя с некоторыми исправлениями ошибок я сделал, набирая код в вопросе. Редактирование: 'scope.PriceCalculatorControl = PriceCalculatorControl' должно было быть' scope.control = control' и 'controller ...' должно быть 'control..' этот' PriceCalculatorControl [2](); 'не нужно. благодаря –

Смежные вопросы