AngularJS模板与指令中的templateURL

Bog*_*dan 5 javascript angularjs angularjs-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'));
                    }
                });
            }
        };
    }]);
Run Code Online (Sandbox Code Playgroud)

"templateUrl"返回指定的模板返回如下内容:

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

在ItemLibraryController中,我定义了在textarea上的keyup上访问的方法commentPost().问题是,$scope.textComment = undefined而不是在textarea中输入的值.如果我在html中修改,ng-model="$parent.textComment"那么找到textarea中的值$scope.textComment.

PS.在指令定义中使用"template"而不是"templateUrl"时,ng-model问题消失了.

我的问题是:

  1. 为什么我必须使用$ parent.textComment,因为模板的范围是ItemLibraryController?

  2. 为什么使用templateUrl为模板内的ng-models创建另一个范围?

  3. 为什么在指令定义中使用"template"而不是"templateUrl"时,ng-model问题会消失?

  4. 如何在不使用$ parent.textComment的情况下访问textComment?

Pan*_*kar 1

解决这个问题的方法是使用 AngularJS , so that the object will for [**prototypal inheritance**][1]. For that you need to create and object and add thetextComment in it, so the object will look like$scope.library={} thentextComment will be placed in it. Also you need to make addrange: true` 的点规则来表示该指令将遵循对象的继承。

模板

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

指示

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
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)