我有两个按钮。当按下时,它显示一个模式,带有som文本。但我也想动态添加一些html,具体取决于按下哪个按钮。
我已经尝试了$observe
和$watch
方法,但是我在使它工作时出现问题。
这是我的代码。
angular.module('TM', [])
.controller('protocolCtrl', function(){
this.text = 'Now looking at the protocol part';
this.modalId = 'protocolModal';
})
.controller('categoryCtrl', function(){
this.text = 'Now looking at the category part';
this.modalId = "categoryModal";
})
.directive('modalDirective', function(){
return {
restrict: 'E',
scope: {
ctrl: '=',
modalId: '@',
},
template: ['<div id="{{modalId}}" class="modal fade" role="dialog">',
'<div class="modal-dialog">',
'<div class="modal-content">',
'<div class="modal-header">',
'<h4 class="modal-title">Modal Header</h4>',
'</div>',
'<div class="modal-body">',
'<p> {{ ctrl.text }} </p>',
'</div>',
'<div class="modal-footer">',
'<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>',
'</div>',
'</div>',
'</div>',
'</div>'].join(''),
link: function(scope, element, attrs) {
element.$observe('modalId', function(){
var modal = element.find('#{{modalId}}');
if(modal == 'protocolModal'){
element.find('#{{modalId}}').append('<div>this is a protocol test...</div>');
} else {
element.find('#{{modalId}}').append('<div>this is a category test...</div>');
}
});
}
}
});
您不需要手动'$ watch'或'$ observe'。如果模板由'$ scope.modalId'控制,那么使用'ng-if'来选择正在显示的内容,例如:'
@NewDev嗯,我也会尝试。但我真的很感激它,如果你能告诉我什么我需要改变我的小提琴来使它与'$观察'或'$ watch'以及:) –
我不认为有'元素。$ observe' - 有'attrs。$ observe'和'scope。$ watch'。无论如何,这里你去:https://jsfiddle.net/L0jns64m/ –