Ste*_*and 2 angularjs angularjs-directive
我想从自定义指令输出一些标记,但仅当模型包含一些文本时.
我几乎就在那里,但我不太确定如何在模型改变时打开/关闭模板,如果这甚至是最有效的方式.
这是标记:
<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>
Run Code Online (Sandbox Code Playgroud)
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;
}]);
Run Code Online (Sandbox Code Playgroud)
并举例说明JSFiddle
如果我理解你想做什么,最简单的方法就是用ng-show.然后你甚至不需要$watch(或链接功能)
app.directive('searched', function(){
return {
restrict: 'E',
replace: true,
scope: {
keywords: '=ngModel'
},
template: '<span ng-show="keywords.length > 0"><span class="field">You searched for:</span> {{ keywords }}</span> '
};
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4685 次 |
| 最近记录: |