javascript - Angular: require injected controller from module -


i'm trying use require function in custom directives. cannot make work. i've got:

js:

var app = angular.module('main', []); app.controller('mycontroller', ['$scope', function($scope){         var random = math.random()*10000;     console.log('init random: ' + random);     $scope.test = function(controllername){         console.log(controllername + " " + random);     }   }]);    app.directive('mydirective', function(){     return{       require: "^mycontroller",       link: function(scope, els, attrs, req){         scope.test('mydirective');       }     }   });     app.directive('myseconddirective', function(){     return{       require: "^mycontroller",       link: function(scope, els, attrs, req){         scope.test('myseconddirective');       }     }   }); 

html:

<div ng-app="main" ng-controller="mycontroller">     <my-directive></my-directive>     <my-second-directive></my-second-directive>   </div> 

https://jsfiddle.net/hr8thyq5/3/

all error message: controller 'mycontroller', required directive 'mydirective', can't found!

what else have make work?

need understand cause -

if want share same instance of controller, use require.

require ensures presence of directive , includes controller parameter link function. if have 2 directives on 1 element, directive can require presence of other directive , gain access controller methods. common use case require ngmodel.

^require, addition of caret, checks elements above directive in addition current element try find other directive. allows create complex components "sub-components" can communicate parent component through controller great effect. examples include tabs, each pane can communicate overall tabs handle switching; accordion set ensure 1 open @ time; etc.

in either event, have use 2 directives work. require way of communicating between components.

for further understanding go here : enter link description here


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -