今天我有一个问题,我需要在ng-model =“element”的输入中添加一个值,但如果我使用ng-model =“model.element”不再适用于我,这里代码< / p>
<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
}
})
这里是codepen:http://codepen.io/fernandooj/pen/EgmQmJ
答案 0 :(得分:1)
当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
}
})