Having a directive that utilizes ng-model controller and fetches its model value from the parent controller, "myController", I am seeking guidance on how to enable the consumer to dynamically set the ngModel value as they desire. The directive is designed for general use and I want my colleagues to be able to reuse it easily. Within the directive, I understand that I can use methods like ngModel.$setValue or $setViewValue, but I am still exploring the intricacies of angularjs directives. Do I need to incorporate a controller inside the directive? Although I am aware that directives have the capability to define controllers, I am unsure about the best practices for doing so. Additionally, is it acceptable to transclude controllers into directives, such as in the case of "nestedInDirController"? Any tips, examples, or advice would be greatly appreciated.
<div ng-controller="myController">
<div foo-directive="" ng-model="viewModel.foo">
<div ng-controller="nestedInDirController">
<various-controls-in-here />
</div>
</div>
</div>
angular.module('myApp', [])
.directive('fooDirective', function(){
var template = '<div><div ng-transclude></div> <button ng-click="someFunc()">I want to update ng-model in the directive, which in turn will update myController $scope.viewModel.foo</button></div>';
return {
transclude: true,
require: '?ngModel',
template: template,
compile: function(tElement, tAttrs, transclude){
return function(scope, element, attrs, ngModel){
}
}
};
});
function myController($scope){
$scope.viewModel = { foo : { bar: 'baz'}};
}
function nestedInDirController($scope){
$scope.someFunc = function(){
alert('I was called');
//how can I set ng-model in foo-directive from this controller?
}
}