AngularJS ng-model-options getter-setter

假如想象 提交于 2019-11-27 12:48:06
Dragos Rusu

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.

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!