Imagine having this sample HTML:
<div ng-controller="MyCtrl">
<br>
<my-directive my-name="name">Hello, {{name}}!</my-directive>
</div>
accompanied by a basic controller:
myApp.controller('MyCtrl', function ($scope) {
$scope.name = 'Superhero';
});
Now in the directive, there is an attempt to change the 'name'
using require
as shown below:
myApp.directive('myDirective', function($timeout) {
var controller = ['$scope', function ($scope) {
$scope.name = "Steve";
}];
return {
restrict: 'EA',
require: 'myName',
controller: controller,
link: function(scope, element, attrs, TheCtrl) {
TheCtrl.$render = function() {
$timeout(function() {
TheCtrl.$setViewValue('StackOverflow');
}, 2000);
};
}
};
});
However, an error is thrown stating:
Error: No controller: myName
You can check out the details in this fiddle
On the contrary, if ng-model is used, it actually works. Explore the working example in another fiddle
According to resources like this article, when utilizing 'require'
in a directive, a controller needs to be present.
Hence, the question arises:
Is the approach being taken incorrect? Should something else be done instead?