Here is how I have defined a directive:
app.directive('itemComments', ['ajax', function(ajax) {
return {
restrict: 'A',
templateUrl: URL + 'public/Pages/Homepage/ajax/getCommentsTpl',
controller: 'ItemLibraryController',
controllerAs: 'itemLibraryCtrl',
link: function(scope, element, attr) {
var $element = $(element);
scope.$watch(function(scope) {
return $element.find('li').length > 0;
}, function(finished) {
if(finished) {
autosize($element.find('textarea'));
}
});
}
};
}]);
The content served by the "templateUrl"
looks something like this:
...
<textarea class="form-control textarea-resize" ng-keyup="commentPost($event)" ng-model="textComment"></textarea>
...
Within ItemLibraryController, there is a method called commentPost() that is triggered on keyup in the textarea. However, instead of capturing the entered value, $scope.textComment
remains undefined. If I change ng-model="$parent.textComment"
in the HTML, then the value from the textarea is stored in $scope.textComment
.
By using "template" in place of "templateUrl" in the directive definition, the issue with ng-model is resolved.
I'm curious about the following:
Why do I need to use $parent.textComment when the template's scope is within ItemLibraryController?
Why does using templateUrl create a separate scope for ng-models inside the template?
Why does changing from "templateUrl" to "template" fix the ng-model problem in the directive?
Is there a way to access textComment without relying on $parent.textComment?