gpt4 book ai didi

javascript - 指令中的 AngularJS 模板与 templateURL

转载 作者:搜寻专家 更新时间:2023-11-01 04:36:17 25 4
gpt4 key购买 nike

我有一个这样定义的指令:

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" 然后文本区域的值在 $scope.textComment 中找到。

附言。当在指令定义中使用“template”而不是“templateUrl”时,ng-model 问题就消失了。

我的问题是:

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

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

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

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

最佳答案

解决这个问题的问题是使用 AngularJS 的点规则,这样对象就可以 [**原型(prototype)继承**][1]。为此,您需要创建对象并在其中添加 textComment,因此对象看起来像$scope.library={}thentextComment 将被放置在其中。此外,您还需要添加 scope: 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
}
};
}]);

关于javascript - 指令中的 AngularJS 模板与 templateURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30829949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com