0

i am learning angular. so reading many post and article for angular. this time i do not understand a particular area in code. code taken from https://stackoverflow.com/a/26741697/728750

<label ng-repeat="fruitName in ['apple', 'orange', 'pear', 'naartjie']">
  <input
    type="checkbox"
    ng-model="fruitsGetterSetterGenerator(fruitName)" 
    ng-model-options="{ getterSetter: true }"
  > {{fruitName}}
</label>

$scope.fruits = ['apple', 'pear']; // pre checked

$scope.fruitsGetterSetterGenerator = function(fruitName){
    return function myGetterSetter(nowHasFruit){
        if (nowHasFruit !== undefined){
            // setter
            fruitIndex = $scope.fruits.indexOf(fruit);
            didHaveFruit = (fruitIndex !== -1);
            mustAdd = (!didHaveFruit && nowHasFruit);
            mustDel = (didHaveFruit && !nowHasFruit);
            if (mustAdd){
                $scope.fruits.push(fruit);
            }
            if (mustDel){
                $scope.fruits.splice(fruitIndex, 1);
            }
        } else {
            //getter
            return $scope.user.fruits.indexOf(fruit) !== -1;
        }
    }
}

do not understand the above code.

the problem lies here. see the code below

$scope.fruitsGetterSetterGenerator = function(fruitName){
    return function myGetterSetter(nowHasFruit){}
}

fruitsGetterSetterGenerator is a function and it return another function from it myGetterSetter in it first line this kind of approach or pattern is not clear to me. please help me to understand. thanks

Community
  • 1
  • 1
Mou
  • 15,673
  • 43
  • 156
  • 275
  • 1
    Function returns something, that can be - object, function -- whats the problem? – Petr Averyanov Apr 06 '16 at 10:00
  • `ng-model` expects an object but here `ng-model="fruitsGetterSetterGenerator(fruitName)"` we have function invocation that will return an object. So it is time to tell AngularJS that it should execute our function so it will have access to returned object. – Krzysztof Safjanowski Apr 06 '16 at 10:21
  • The answer and the documentation it links to explain the approach. I'm not sure what else you need to know. – a better oliver Apr 06 '16 at 10:24
  • when the function myGetterSetter() will be called and who will call it? – Mou Apr 06 '16 at 10:47
  • anyone can help me to understand the posted code. – Mou Apr 06 '16 at 18:01

0 Answers0