Вопрос

I started a new project in angularjs with angular-seed. I tried to add some directive, without success.

The goal is, I have 2 choices/fields in my controller and would like to generate the fields for this choices.

I get always the Error: Unknown provider: $scopeProvider <- $scope <- gendivDirective

is there a dependecy injection needed or something else? Or is it the wrong scope? The Controller should be available in the directives?

Thanks, Patrick

test.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>

script.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");
    }
}
  }]);
Это было полезно?

Решение

You can't inject $scope into a directive. It is passed to the link function anyway, so you shouldn't need to. I don't actually see you using it anywhere in your code.

Другие советы

Keep in mind you are resetting your controller...

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......
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top