【发布时间】:2017-09-28 06:44:33
【问题描述】:
这是我的控制器
function commentController($stateParams, commentFactory, $rootScope){
const ctrl = this;
ctrl.comment = {};
ctrl.decision = {};
ctrl.$onInit = function(){
ctrl.decision.replyVisible = false;
}
export {commentController}
这是我的组件
import {commentController} from './comment.controller'
export const commentComponent = 'commentComponent'
export const commentComponentOptions = {
bindings: {
post: '<'
},
templateUrl: 'blog/src/app/components/post/comment/comment.html',
controller: ['$stateParams', 'commentFactory', '$rootScope', commentController],
controllerAs: 'cm'
}
这是我的指令
function showReply(){
return {
restrict: 'A',
scope: {
collapsed: '<'
},
link: function(scope, element, attrs){
element.on('click', ()=>{
console.log(`Trying to hide ${scope.collapsed}`);
scope.collapsed = true
console.log(`Trying to hide ${scope.collapsed}`);
})
}
}
}
function hideReply(){
return {
restrict: 'A',
scope: {
collapsed: '<'
},
link: function(scope, element, attrs){
element.on('click', ()=>{
scope.collapsed = false;
console.log(`Trying to hide scope.replyVisible is ${scope.collapsed}`);
})
}
}
}
export {showReply, hideReply}
这是我的html
<div class="comment_wrapper">
<div class="comment" ng-repeat="comment in cm.post.comments">
<h3>{{comment.author.name}}</h3>
<a href="" ng-hre="mailto:{{comment.author.email}}"></a>
<p ng-bind-html="comment.comment"></p>
<button show-reply collapsed="cm.decision.replyVisible">Reply</button>
<div class="reply_wrapper" ng-show="cm.decision.replyVisible">
<label for="name">Name</label>
<input type="text" id="name" ng-model="cm.comment.author.name">
<label for="email">Email</label>
<input type="text" id="email" ng-model="cm.comment.author.email">
<label for="comment">Comment</label>
<textarea name="" id="comment" cols="10" rows="5" ng-model="cm.comment.comment"></textarea>
<button ng-click="cm.reply(comment._id)">Submit</button> <button hide-reply collapsed="cm.decision.replyVisible">Cancel</button>
</div>
</div>
</div>
这是我的模块
import angular from 'angular'
import {showReply, hideReply} from './comment.directive'
import {commentFactory, commentFactoryFunc} from './comment.factory'
import {commentComponent, commentComponentOptions} from './comment.component'
export const comment = angular.module('comment', [uiRouter])
.factory(commentFactory, ['$http', commentFactoryFunc])
.component(commentComponent, commentComponentOptions)
.directive('showReply', showReply)
.directive('hideReply', hideReply)
.name
这就是我想要做的,在我的 html 中,我想在有人点击回复按钮时显示回复表单。而且由于有多个 cmet,每个都有一个回复表单,我不能使用常规的 ng-click。
对scope.collapsed 所做的更改不会反映在cm.decision.replyVisible 上
我该如何进行这项工作?我一直对从指令访问父控制器变量感到困惑。
【问题讨论】:
-
可能是因为你使用了单向绑定
post: '<'尝试post: '=' -
这不是关于
post我试图隐藏回复表单。而且,我试图避免双向数据绑定,正如很多人在引入 Angular 1.5 时提到的那样 -
是的,对不起,它是关于
collapsed: '=',如果你想从孩子改变父母的东西,你需要使用双向绑定。 -
但是我对每条评论都有一个回复表。如果我通过双向数据绑定绑定
collapsed,那么它也会反映其他回复表单上的更改。 -
是的,你需要在
comment.decision.replyVisible而不是cm中保持状态collapsed
标签: angularjs angularjs-directive angularjs-components