Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-model-options getter-setter

Tags:

I've just upgrade to angular version 1.3.8.

When using 1.2.23 version I've created a directive to convert the data form view to model and vice verse.

This is my directive:

.directive('dateConverter', ['$filter', function ($filter) {

    return {

        require: 'ngModel',

        link: function (scope, element, attrs, ngModelController) {

            // Convert from view to model
            ngModelController.$parsers.push(function (value) {
                return $filter('date')(new Date(date), 'yyyy-MM-ddTHH:mm:ss')
            });

            // Convert from model to view
            ngModelController.$formatters.push(function (datetime) {
                return $filter('date')(datetime, 'MM/dd/yyyy');
            });
        }
    };
}]);

});

I see here that getters and setters in binding are now supported, but I cannot find anywhere how to use both getters and setters. Is there any way to do it? That is - can ng-model-options replace my convert directive?

Thanks

like image 869
user2717436 Avatar asked Jan 13 '15 09:01

user2717436


People also ask

What is [( ngModel )]?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

What is NG model options Debounce?

The updateOn and debounce properties allow you to specify a custom list of events that will trigger a model update and/or a debouncing delay so that the actual update only takes place when a timer expires; this timer will be reset after another change takes place.

What is NG model in AngularJS?

AngularJS ng-model Directive The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

What is difference between ng model and Ng bind?

ngModel usually use for input tags for bind a variable that we can change variable from controller and html page but ngBind use for display a variable in html page and we can change variable just from controller and html just show variable.


2 Answers

The documentation might seem a bit fuzzy but the usage is quite simple. What you need to do:

  1. HTML:

    <input ng-model="pageModel.myGetterSetterFunc"
    ng-model-options=" {getterSetter: true }">
    
  2. in JS controller, instead of the actual model, create a function that will return the value (+ apply stripping) if the there is no parameter sent and that will update the model (+ apply other changes) if a parameter is sent.

The getter/setters is basically another "layer" between the view value and model value.

Example:

$scope.pageModel.firstName = '';
$scope.pageModel.myGetterSetterFunc: function (value) {
  if (angular.isDefined(value)) {
    $scope.pageModel.firstName = value + '...';
  } else {        
    return $scope.pageModel.firstName.substr(0,
      $scope.pageModel.firstName.lastIndexOf('...')
    );
  }
}

DEMO PLUNKER: http://plnkr.co/edit/Zyzg6hLMLlOBdjeW4TO0?p=preview

(check console - http://screencast.com/t/3SlMyGnscl)

NOTE: It would be interesting to see how would this scale in terms of reusability. I would advise to create these getter/setters as externalized reusable methods and have generators for them (because the data model is different for each case). And in controllers to only call those generators. Just my 2 cents.

like image 185
Dragos Rusu Avatar answered Sep 18 '22 17:09

Dragos Rusu


This question is rather old - but for IE9+ (and of course all other relevant browsers) you can use the ECMAScript 5 getter/setter methode which I would prefer against the getterSetter option of ng-model:

var person = {
    firstName: 'Jimmy',
    lastName: 'Smith',
    get fullName() {
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}

person.fullName = 'Jack Franklin';
console.log(person.firstName); // Jack
console.log(person.lastName) // Franklin

This example is from http://javascriptplayground.com/blog/2013/12/es5-getters-setters/

like image 21
Gerfried Avatar answered Sep 18 '22 17:09

Gerfried