2015-10-19 82 views
0

我要創建指令:爲什麼我在嘗試創建指令時出錯?

這裏是指令的定義:

(function() { 
    "use strict"; 

    angular.module("siteObjects").directive("myOnOffSwitch", [myOnOffSwitch]); 

    function myOnOffSwitch() { 
     return { 
      restrict: "E", 
      scope: { 
       status: "=", 
      }, 
      template: "<div class='well'>"+ 
         "<i class='fa fa-toggle-on active' ng-if='status == true' ng-click='changeStatus();'></i>"+ 
         "<i class='fa fa-toggle-on fa-rotate-180 inactive' ng-if='status == false' ng-click='changeStatus();'></i>"+ 

         "<div style='display: inline-block;font-size: 30px; float:left;' ng-if='status == true'> on</div>" + 
         "<div style='display: inline-block;font-size: 30px; float:left;' ng-if='status == false'>off</div>" + 
         "</div>", 

      controller: function ($scope) { 

       $scope.changeStatus = function() { 
        $scope.status = !$scope.status; 
       } 
      } 
     } 
    } 
})(); 

在這裏,我如何使用它在我的觀點:

<my-on-off-switch status="list.status"></my-on-off-switch> 

我得到這個錯誤:

Error: [$injector:strictdi] function($scope) is not using explicit annotation and cannot be invoked in strict mode 

任何想法,爲什麼我得到上述錯誤?

+0

我會建議使用'bindToController',這樣你就不必注入'$ scope',這樣你的代碼變得更加清晰 – LionC

回答

0

我想這個錯誤是因爲嚴格模式的使用,並且您正在調用未明確註釋的提供程序($ scope)。爲了解決這個問題,你可以使用$注入性...

function myOnOffSwitchController($scope) { 
    $scope.changeStatus = function() { 
     $scope.status = !$scope.status; 
    } 
} 

myOnOffSwitchController.$inject = ["$scope"]; 

...和他們,在你的指令:

function myOnOffSwitch() { 
    return { 
     ... 
     controller: myOnOffSwitchController 
     ... 
    } 
} 

https://code.angularjs.org/1.3.15/docs/error/ $噴油器/ strictdi

相關問題