javascript - Angular custom directive: a strange error occurs when set controller attribute to `function(scope){}` -
when wrote custom directive, strange error blocks me.
angular.module('app.directives', []) .directive('cymenu', ['recursionhelper', function(recursionhelper) { function postlink(){}; return { restrict: 'e', templateurl: 'views/component/cy-menu.html', replace: true, transclude: false, require: '?^cymenu', controller: function ($scope) { // when set argument($scope) scope, error occurs. this.getlist = function() { return $scope.list; } }, scope: { list: '=', issubmenu: '@' }, compile: function(telement) { return recursionhelper.compile(telement, postlink); } } }
as pointed out(see comment), when set controller
attribute controller: function (scope) {}
, error occurs:
error: [$injector:unpr] unknown provider: scopeprovider <- scope http://errors.angularjs.org/1.3.6/$injector/unpr?p0=scopeprovider%20%3c-%20scope ...
i don't know why. appreciated.
update
here angular's official demo, looks similar directivehttps://code.angularjs.org/1.3.6/docs/guide/directive:
angular.module('docstabsexample', []) .directive('mytabs', function() { return { restrict: 'e', transclude: true, scope: {}, controller: function($scope) { ... }, templateurl: 'my-tabs.html' }; })
a practice separate every component in separate file, start putting controller in file :
//file recursionhelpercontroller.js (function() { 'use strict'; angular .module('app.controllers') .controller('recursionhelpercontroller', recursionhelpercontroller); recursionhelpercontroller.$inject = ['$scope']; function recursionhelpercontroller($scope) { //do stuff } })();
note gave correct format know controller or angular element in general, can simpler like:
angular.module('app.controllers') .controller('recursionhelpercontroller', ['$scope', function($scope) { //do stuff }])
you can call controller in main file :
controller: 'recursionhelpercontroller'
hope helps
update :
sometimes automatic injection has troubles that's why recommend doing way explicit injection. angular doc shows simplest way clarity , tutorial purposes
update 2
if don't want separate controller, try using injection safe notation
controller : ['$scope', function($scope) { //do stuff }])
Comments
Post a Comment