我用 angular-seed 在 angularjs 中开始了一个新项目。我试图添加一些指令,但没有成功。
目标是,我的控制器中有 2 个选项/字段,并希望为此选项生成字段。
我总是得到错误:未知提供者:$scopeProvider <- $scope <- gendivDirective
是否需要依赖注入或其他?还是范围不对?控制器应该在指令中可用?
谢谢,帕特里克
测试.html:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<div ng-controller="FormCtrl">
<span gendiv>
</span>
</div>
</body>
</html>
脚本.js:
angular.module('myApp', ['myApp.directives','myApp.controllers']);
/* Controllers */
angular.module('myApp.controllers', [])
.controller('FormCtrl', ['$scope', function ($scope) {
$scope.choices = {
object: [
{label: "Choice0"},
{label: "Choice1"}
]
};
$scope.addChoice = function() {
$scope.choices.object.push({
label: 'Choice' + $scope.choices.object.length.toString()
});
};
}]);
/* directives */
angular.module('myApp.directives', [])
.directive('gendiv', ['$scope', function($scope) {
return {
controller: 'FormCtrl',
template: '<div class="control-group" ng-repeat="choice in choices.object">' +
'<label class="control-label" for="{{choice.label}}">{{choice.label}}</label>' +
'<div class="controls" style="color: #0044cc">' +
'<input type="text" placeholder="Enter second choice here" name="choices[]" data-ng-model="choices[]" required> <i class="icon-plus-sign icon-large" style="padding-left:10px;cursor: pointer" alt="add choice" ng-click="addChoice()" class="add"></i>' +
'</div>' +
'<span ng-show="myForm.name.$error.required" class="help-inline">Required</span>' +
'</div>',
link: function (scope, elem, attrs) {
console.log("Recognized the directive usage");
}
}
}]);