如何在自定义指令中获取评估属性我试图从我的自定义指令获取一个评估属性,但我找不到正确的方法。我已经创建了这个jsFiddle来详细说明。<div ng-controller="MyCtrl">
<input my-directive value="123">
<input my-directive value="{{1+1}}"></div>myApp.directive('myDirective', function () {
return function (scope, element, attr) {
element.val("value = "+attr.value);
}
});我错过了什么?
3 回答
胡说叔叔
TA贡献1804条经验 获得超8个赞
对于我正在寻找的相同解决方案Angularjs directive with ng-Model。
这是解决问题的代码。
myApp.directive('zipcodeformatter', function () {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function (scope, element, attrs, ngModel) {
scope.$watch(attrs.ngModel, function (v) {
if (v) {
console.log('value changed, new value is: ' + v + ' ' + v.length);
if (v.length > 5) {
var newzip = v.replace("-", '');
var str = newzip.substring(0, 5) + '-' + newzip.substring(5, newzip.length);
element.val(str);
} else {
element.val(v);
}
}
});
}
};});
HTML DOM
<input maxlength="10" zipcodeformatter onkeypress="return isNumberKey(event)" placeholder="Zipcode" type="text" ng-readonly="!checked" name="zipcode" id="postal_code" class="form-control input-sm" ng-model="patient.shippingZipcode" required ng-required="true">
我的结果是:
92108-2223
添加回答
举报
0/150
提交
取消
