今天我有一个问题,我需要添加一个值的输入与ng-model =" element"的工作,但如果我使用ng-model ="模型。元素"不再适用于我,这里的代码
<div ng-app="myApp" ng-controller="myCtrl as model">
<input type="text" ng-cero="uno" ng-model="c1ero">
<input type="text" ng-cero="dos" ng-model="model.eae" >
</div>
angular
.module("myApp",[])
.controller('myCtrl', function($scope){
var model=this;
})
.directive ('ngCero', function(){
var linkFunction =function(scope, element, attrs){
element.bind("keypress", function(event) {
if(event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.ngCero, {'event': event});
scope[attrs.ngModel]="0,";
console.log(attrs);
});
event.preventDefault();
}
});
};
return{
controller: "myCtrl",
link: linkFunction
}
})
这里是codependency: http://codepen.io/fernandooj/pen/EgmQmJ
当ngModel指向嵌套属性如model.eae时,你需要解析scope[attrs.ngModel]="0,";
。使用angular $parse服务来实现这个目的($parse(attrs.ngModel).assign(scope, '0, ');
):
.directive ('ngCero', function($parse) {
var linkFunction =function(scope, element, attrs) {
element.bind("keypress", function(event) {
if (event.which === 13) {
scope.$apply(function(){
scope.$eval(attrs.ngCero, {'event': event});
$parse(attrs.ngModel).assign(scope, '0, ');
console.log(attrs);
});
event.preventDefault();
}
});
};
return {
controller: "myCtrl",
link: linkFunction
}
})