2015-06-14 86 views
5

我有一個指令定義是這樣的:AngularJS模板VS templateURL

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')); 
        } 
       }); 
      } 
     }; 
    }]); 

通過"templateUrl"回報像這樣指定的模板:

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

在ItemLibraryController我已經定義的方法commentPost( )可以在textarea的keyup上訪問。 問題是$scope.textComment = undefined而不是在textarea中輸入的值。如果我在html ng-model="$parent.textComment"中修改,那麼textarea中的值可在$scope.textComment中找到。

PS。在指令定義中使用「template」而不是「templateUrl」時,ng模型問題會消失。

我的問題是:

  1. 爲什麼我必須使用$ parent.textComment因爲模板是ItemLibraryController的範圍是什麼?

  2. 爲什麼使用templateUrl爲模板內的ng模型創建另一個範圍?

  3. 爲什麼在指令定義中使用「template」而不是「templateUrl」時,ng模型問題會消失?

  4. 如何在不使用$ parent.textComment的情況下訪問textComment?

+0

你如何定義'textComment'的父範圍使用'$ scope.textComment'或'this.textComment'值,? –

+0

我使用$ scope.textComment – Bogdan

回答

1

的問題來解決這個問題,將使用的AngularJS , 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範圍:TRUE`地說,指令將按照對象的繼承。

模板

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

指令

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 
     } 
    }; 
}]); 
+0

嗯..我已經在指令的「link」方法中創建了一個像scope.library = {textComment:''}這樣的本地對象,然後我使用了ng-model =「library.textComment 「而且它在指令中沒有使用」範圍:真「。所以我會將這個答案標記爲可接受的,因爲它將我推向了正確的道路。 – Bogdan