为什么我在尝试创建指令时出错?
问题描述:
我要创建指令:为什么我在尝试创建指令时出错?
这里是指令的定义:
(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
任何想法,为什么我得到上述错误?
答
我想这个错误是因为严格模式的使用,并且您正在调用未明确注释的提供程序($ 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
我会建议使用'bindToController',这样你就不必注入'$ scope',这样你的代码变得更加清晰 – LionC