为什么我在尝试创建指令时遇到错误?

时间:2015-10-19 08:37:28

标签: angularjs

我想创建指令:

这是指令定义:

(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

我知道为什么会出现上述错误?

1 个答案:

答案 0 :(得分:0)

我想错误即将发生,因为使用严格模式并且您正在调用尚未明确注释的提供程序($ scope)。要修复它,你可以使用$ inject属性...

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/ $ injector / strictdi