Thilaga
Thilaga

Reputation: 1621

angular directive scope[attrs.ngModel] is not working

if the user input is not a number, i have to revert to old number value.

setting scope value from directive is not working.

http://jsfiddle.net/vfsHX/149/

app.directive('isNumber', function () {
    return {
  require: 'ngModel',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function(newValue,oldValue) {
            var arr = String(newValue).split("");
            if (arr.length === 0) return;
            if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
            if (arr.length === 2 && newValue === '-.') return;
            if (isNaN(newValue)) {
                console.log(oldValue);
                scope[attrs.ngModel] = oldValue;
            }
        });
    }
};
});

Upvotes: 0

Views: 1125

Answers (2)

Thilaga
Thilaga

Reputation: 1621

use of $setViewValue solves the issue

http://jsfiddle.net/vfsHX/158/

if(isNaN(newValue))             
{
ngModel.$setViewValue(oldValue);
ngModel.$render();
}

Upvotes: 1

Kavitha K Gowd
Kavitha K Gowd

Reputation: 527

Your model is in nested form hence when you try to access using scope[attrs.ngModel], you are referening to model which is not there. Instead of using the nested javascript model if you directly give a reference then its working. Check out the fiddle here http://jsfiddle.net/ztUsc/1/

Upvotes: 0

Related Questions