0

我用 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");
    }
}
  }]);
4

2 回答 2

2

您不能将 $scope 注入指令。无论如何,它都会传递给链接函数,因此您不需要这样做。我实际上并没有看到您在代码中的任何地方使用它。

于 2013-07-17T00:47:10.790 回答
0

请记住,您正在重置控制器...

angular.module('myApp', ['myApp.directives','myApp.controllers']);

/* Controllers */

angular.module('myApp.controllers', []) // YOU ARE RESETTING YOUR CONTROL TRY THIS

var app = angular.module('myApp', ['myApp.directives','myApp.controllers']);
    app.controller......
于 2014-06-19T05:12:47.527 回答