2
我想输出从自定义指令一些标记,但前提是该模型包含一些文本。AngularJS - 隐藏/显示指令输出基于表达式
我几乎没有,但我只是不很清楚如何打开/关闭时的模式变化的模板,如果这是连这样做的最有效的方式。
下面是标记:
<div data-ng-controller="test">
<div class="box">
<input type="text" id="search" maxlength="75" data-ng-model="keywords" />
</div>
<searched data-ng-model="keywords"></searched>
</div>
的JS:
var app = angular.module('myApp', []);
app.directive('searched', function(){
return {
restrict: 'E',
replace: true,
scope: {
keywords: '=ngModel'
},
template: '<span><span class="field">You searched for:</span> {{ keywords }}</span> ',
link: function(scope, element, attrs) {
scope.$watch('keywords', function(newVal, oldVal){
if(newVal === null) {
// Output nothing!
} else {
// Output Template as normal.
}
}, true);
}
};
});
app.controller("test", ['$scope', function($scope) {
$scope.keywords = null;
}]);
和示例JSFiddle
精湛,非常感谢这一点。我知道我已经结束了它:) – 2013-03-14 19:12:11
反思,是一个指令甚至值得使用这个?我真正想要做的就是现在模板中的内容。我应该使用实际标记中的模板中的内容吗?我已经在标记中试过了,它正是我想要的,所以是一个指令矫枉过正? – 2013-03-15 09:00:32
如果你不需要在其他地方重复使用相同的标记,那么是的,该指令可能是矫枉过正的。当您不想在多个地方重复相同的标记时,该指令很方便。 – dnc253 2013-03-15 15:47:40