我有一个自定义指令,希望在页面上的多个元素上使用。我很难隔离范围并显示基于子范围的元素。这是我要执行的操作的一个示例:
app.js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
})
.directive('comShowLabelOnFocus', function() {
return {
restrict: 'A',
scope: {
showlabel: '='
},
link: function(scope) {
scope.inputClicked = function() {
event.currentTarget.placeholder = '';
scope.showlabel = true;
};
}
}
});
index.html:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div class="form-group medium-6 columns" com-show-label-on-focus>
<input
type="email"
name="email"
ng-model="model.email"
placeholder="Your Email Address"
ng-click="inputClicked()"/>
<label ng-show="showlabel">Email Address (Required)</label>
showlabel is: {{showlabel}}
</div>
<div class="form-group medium-6 columns" com-show-label-on-focus>
<input
type="text"
name="name"
ng-model="model.name"
placeholder="Your Name"
ng-click="inputClicked()"/>
<label ng-show="showlabel">Name (Required)</label>
showlabel is: {{showlabel}}
</div>
</body>
行动中:Plunker
基本上,当字段聚焦时,字段标签应该出现。如果我在指令中注释了该范围声明,则showlabel scope变量是根范围,并且会出现BOTH标签。谢谢。
首先,您期望内部div
带有属性指令的标记的功能类似于指令的模板。这将无法正常工作。
让我们在指令对象的template
或templateUrl
中为您的指令定义标记:
return {
//other properties
template: '<input type="text" name="name" ng-model="model.name" placeholder="{{myPlaceholder}}" ng-click="inputClicked()"/> <label ng-show="showlabel">{{myLabel}}</label>showlabel is: {{showlabel}}',
}
接下来,设置作用域以正确使用模板,并且不要绑定到showlabel。该指令可以在其隔离范围内对其进行管理:
scope: {
myPlaceholder: '@',
myLabel: '@'
}
最后,让我们看看Angular文档restrict
对控制其模板的指令的属性要说些什么:
什么时候应该使用属性而不是元素?创建由模板控制的组件时,请使用元素。常见的情况是在为模板的一部分创建特定于域的语言时。使用新功能装饰现有元素时,请使用属性。
因此,由于您的指令确实控制其模板,因此应将其限制为一个元素。
最后,您的指令javascript可能看起来像这样:
.directive('comShowLabelOnFocus', function() {
return {
restrict: 'E',
scope: {
myPlaceholder: '@',
myLabel: '@'
},
template: '<input type="text" name="name" ng-model="model.name" placeholder="{{myPlaceholder}}" ng-click="inputClicked()"/> <label ng-show="showlabel">{{myLabel}}</label>showlabel is: {{showlabel}}',
link: function(scope) {
scope.showlabel = false;
scope.inputClicked = function() {
event.currentTarget.placeholder = '';
scope.showlabel = true;
};
}
}
});
像这样的标记:
<com-show-label-on-focus data-my-placeholder="Your Name" data-my-label="Name (Required)"></com-show-label-on-focus>
对于所有修改,我深表歉意。起初,我误读了您的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句