Reputation: 329
today I have a question, I need to add a value to an input with ng-model = "element" works but if I use ng-model = "model.element" no longer works for me, here the code
<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
}
})
and here the codepen: http://codepen.io/fernandooj/pen/EgmQmJ
Upvotes: 0
Views: 82
Reputation: 15442
you need to parse scope[attrs.ngModel]="0,";
when ngModel points to nested property like model.eae. Use angular $parse service for this purpose ($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
}
})
Upvotes: 1