AngularJS vs templateURL template in directive

I have a directive defined as follows:

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 template specified by "templateUrl" returns the following:

 ... <textarea class="form-control textarea-resize" ng-keyup="commentPost($event)" ng-model="textComment"></textarea> ... 

In ItemLibraryController, I defined the commentPost () method, which is accessed in keyup on textarea. The problem is that $scope.textComment = undefined instead of the value entered in textarea. If I change in html ng-model="$parent.textComment" , then the value from the text field is in $scope.textComment .

PS. When using a "template" instead of "templateUrl" in the definition of the directive, the ng model problem disappears.

My questions:

  • Why do I have to use $ parent.textComment since the scope of the template is ItemLibraryController?

  • Why does using templateUrl create another area for ng models inside the template?

  • Why, when defining a "template" instead of "templateUrl" in the definition of a directive, does the ng model problem disappear?

  • How can I access textComment without using $ parent.textComment?

+5
source share
1 answer

The problem to solve this problem will be to use the AngularJS dot rule , so that the object will for [**prototypal inheritance**][1]. For that you need to create and object and add the , so that the object will for [**prototypal inheritance**][1]. For that you need to create and object and add the textComment in it, so the object will look like $ scope.library = {} then textComment will be placed in it. Also you need to make add will be placed in it. Also you need to make add scope: true` to say that the directive will follow the inheritance of the object.

Template

 ... <textarea class="form-control textarea-resize" ng-keyup="commentPost($event)" ng-model="library.textComment"> </textarea> ... 

Directive

 app.directive('itemComments', ['ajax', function(ajax) { return { scope: true, //<--added here restrict: 'A', templateUrl: URL + 'public/Pages/Homepage/ajax/getCommentsTpl', controller: 'ItemLibraryController', controllerAs: 'itemLibraryCtrl', link: function(scope, element, attr) { //code here } }; }]); 
+1
source

All Articles