Quello che sto cercando di ottenere è aggiungere un'interfaccia extra per i campi di input per poter aumentare e diminuire il valore numerico in essi facendo clic sui pulsanti + e -.Come aggiornare il modello AngularJS dalla funzione di collegamento direttiva?
(In sostanza è quello che i campi di input [type = number] hanno su chrome, ma voglio che questo sia compatibile con cross-broswer e che abbia anche il pieno controllo della presentazione su tutti i browser).
Codice in vista:
<input data-ng-model="session.amountChosen" type="text" min="1" class="form-control input-small" data-number-input>
codice direttiva:.
app.directive('numberInput', function() {
return {
require: 'ngModel',
scope: true,
link: function(scope, elm, attrs, ctrl) {
var currValue = parseInt(scope.$eval(attrs.ngModel)),
minValue = attrs.min || 0,
maxValue = attrs.max || Infinity,
newValue;
//puts a wrap around the input and adds + and - buttons
elm.wrap('<div class="number-input-wrap"></div>').parent().append('<div class="number-input-controls"><a href="#" class="btn btn-xs btn-pluimen">+</a><a href="#" class="btn btn-xs btn-pluimen">-</a></div>');
//finds the buttons ands binds a click event to them where the model increase/decrease should happen
elm.parent().find('a').bind('click',function(e){
if(this.text=='+' && currValue<maxValue) {
newValue = currValue+1;
} else if (this.text=='-' && currValue>minValue) {
newValue = currValue-1;
}
scope.$apply(function(){
scope.ngModel = newValue;
});
e.preventDefault();
});
}
};
})
Questo è in grado di recuperare il valore attuale modello con portata $ eval (attrs.ngModel) , ma non riesce a impostare il nuovo valore.
Aftermath edit: questo è il codice che ora lavora (nel caso in cui si wan't di vedere la soluzione per questo problema)
app.directive('numberInput', function() {
return {
require: 'ngModel',
scope: true,
link: function(scope, elm, attrs, ctrl) {
var minValue = attrs.min || 0,
maxValue = attrs.max || Infinity;
elm.wrap('<div class="number-input-wrap"></div>').parent().append('<div class="number-input-controls"><a href="#" class="btn btn-xs btn-pluimen">+</a><a href="#" class="btn btn-xs btn-pluimen">-</a></div>');
elm.parent().find('a').bind('click',function(e){
var currValue = parseInt(scope.$eval(attrs.ngModel)),
newValue = currValue;
if(this.text=='+' && currValue<maxValue) {
newValue = currValue+1;
} else if (this.text=='-' && currValue>minValue) {
newValue = currValue-1;
}
scope.$eval(attrs.ngModel + "=" + newValue);
scope.$apply();
e.preventDefault();
});
}
};
})
possono essere 'ctrl. $ SetViewValue (newValue)'? – Cherniv
usa ng-clic e un modello. –
Cherniv, no, non ha fatto il trucco, ma il tuo suggerimento mi ha aiutato a capire meglio Angular. Grazie. –