[英]AngularJS custom directive ng-show/ng-hide
警告:Angular新手提前。
我正在尝试创建一个自定义窗口小部件,默认情况下会显示“回复”链接,单击时,应该隐藏它,并显示textarea。 这是我到目前为止,但它不起作用::
.directive('replybox', function ($rootScope) {
var linkFn = function (scope, element, attrs) {
var label = angular.element(element.children()[0]);
scope.showInput = false;
label.bind("click", textbox);
function textbox() {
scope.showInput = true;
}
};
return {
link:linkFn,
restrict:'E',
scope:{
id:'@',
label:'@',
showInput:'='
},
template:'<a ng-hide="showInput">label</a><textarea ng-show="showInput"> </textarea>',
transclude:true
};
})
任何指南将不胜感激。 谢谢!
Matias,这是一个有用的jsFiddle: http : //jsfiddle.net/pkozlowski_opensource/Z6RzD/
实际上有很多事情发生,但我认为最重要的事情是你需要使用Scope。$ apply以从“anular的世界之外”改变角度通知范围。 默认情况下,angular不会触发模板重新评估每个DOM事件,因此您需要将其包装到apply中:
scope.$apply('showInput = true');
更多信息:http://docs.angularjs.org/api/ng.$rootScope.Scope
您的示例中还有其他值得注意的项目:
你也可以使用$ timeout来通知你的变化角度,例如
.directive('replybox', function($rootScope, $timeout) {
var linkFn = function(scope, element, attrs) {
var label = angular.element(element.children()[0]);
scope.showInput = false;
label.bind("click", textbox);
function textbox() {
$timeout(function() {
scope.showInput = true;
});
}
};
return {
link: linkFn,
restrict: 'E',
scope: {
id: '@',
label: '@',
showInput: '='
},
template: '<a ng-hide="showInput">label</a><textarea ng-show="showInput"> </textarea>',
transclude: true
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.