Javascript 模板中的AngularJS ng模型传递给指令控制器
我有一个带有控制器的指令,它构建了一个表单,用于通过CommentsService向API发布注释 我的指令看起来有点像这样:Javascript 模板中的AngularJS ng模型传递给指令控制器,javascript,angularjs,angularjs-directive,angularjs-scope,angularjs-model,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,Angularjs Model,我有一个带有控制器的指令,它构建了一个表单,用于通过CommentsService向API发布注释 我的指令看起来有点像这样: app.directive('appComments', function( CommentService ) { return { restrict: 'E', scope: { event: '=' }, controller: function( $rootScope,
app.directive('appComments', function( CommentService ) {
return {
restrict: 'E',
scope: {
event: '='
},
controller: function( $rootScope, $scope, $element ) {
$scope.comments = [];
$scope.comment_text = '';
// load comments if event ID has changed
$scope.$watch( 'event', function() {
if( typeof $scope.event != 'undefined' ) {
CommentService.get( $scope.event ).then(
function( comments ) {
$scope.comments = comments;
}
);
}
});
// post comment to service
$scope.postComment = function() {
if( $scope.comment_text != '' ) {
CommentService.post(
$scope.event,
$scope.comment_text,
function() {
// code to reload comments
}
);
}
};
},
templateUrl: '/partials/comments.html'
};
});
这是指令的my comments.html
<div class="event-comments">
<p ng-if="!comments.length">
<span>This event has no comments.</span>
</p>
<div
class="event-comment"
ng-repeat="comment in comments"
>
<div class="comment-text">{{comment.text}}</div>
</div>
</div>
<div class="insert-comment-container" ng-if="!loading">
<form ng-submit="postComment()">
<textarea
ng-model="comment_text"
></textarea>
<div
ng-tap="postComment()"
>Post</div>
</div>
</div>
在指令中,当模板在textarea内呈现时,它会出现,并且postComments()函数中的
if
语句会触发。但是如果我更改文本区域中的文本,并点击post按钮,则$scope.comment\u text
的内容仍然是“初始文本”,似乎是单向绑定。因为您使用的是表单,我相信它创建了一个新的范围。根据文件
如果指定了name属性,则发布表单控制器
此名称下的当前作用域
试着给你的表单起个名字。或者尝试将属性作为对象属性传递,如
<textarea
ng-model="comment.comment_text">
</textarea>
好,将
comment\u text
更改为comment.text
解决了问题,如本so答案所建议:
使用对象而不是原语只是使用对对象属性的相同引用,而不是将原语复制到新范围。我在模板中为表单指定了一个名称,
commentform
,但是如果我console.log()
在postComment()期间使用$scope,我看不到commentform。
$scope.comment_text = 'Initial text'
<textarea
ng-model="comment.comment_text">
</textarea>