让我们说我想创建一个模拟数字输入字段的指令(这样做只是为了了解一般的指令)
所以,我创建了一个这样的指令
angular.module('myApp')
.directive('inputNumber',function(){
return {
replace: true,
restrict: 'E',
scope: {
label: '@',
property: '=',
readonly: '@',
disabled: '@'
},
templateUrl: '/directives/numberInput.html'
};
})
并且templateUrl就是这个
<md-input-container>
<label>{{ label }}</label>
<input ng-model="property" type="number">
</md-input-container>
我的html文字就是这个
<input-number label="Columns" property="controller.data.cols">
</input-number>
奇怪的是,这很有效;)第一次尝试给我留下了深刻的印象。
现在,有时我想为数字添加最小和最大属性
因为这些是可选的,我将如何添加到指令js和html?
我认为我添加了
min: '@',
max: '@',
指令js,但是我将什么放入html?
<input ng-model="property" type="number" min="{{min}}" max="{{max}}">
但是如果没有提供min / max会发生什么?
感谢
答案 0 :(得分:0)
您需要在问号上添加。
scope: {
label: '@',
property: '=',
readonly: '@',
disabled: '@',
min: '@?',
max: '@?'
}
问号将范围绑定声明为可选,如果您不需要,则允许您不在标记中包含它们。如果您不包含它们,那么您的隔离范围上的属性将无法定义。
<input ng-model="property" type="number" min="{{min}}" max="{{max}}">
是的,这是使用{{}}
绑定语法将值传递到这些属性的正确方法。这是因为@
绑定是文字绑定。它将获取该属性的原始字符串值,并将其分配给该隔离范围变量。通过使用绑定语法,Angular将在解析指令之前将这些绑定解析为实际值,并在中读取这些值。
如果您想要双向绑定,那么您将使用=
绑定符号。那个告诉angular,你传递给该属性的任何东西都应该是指令周围的父范围的变量。 Angular在那时知道在该外部范围变量和指令的隔离范围上的变量之间创建双向绑定。这样,如果隔离范围中的变量发生变化,则外部变量范围变量也会发生变化,反之亦然。
<input ng-model="property" type="number" min="minValue" max="maxValue">
在该示例中,您的指令期望minValue
和maxValue
是已在指令周围的父作用域上定义的变量。
我去年在隔离范围绑定上写了详细的blog post。希望它有所帮助!