Angular.js model defined in JavaScript, one property needs to be evaluated as a function

I've defined my model in the JS like so:

$scope.requirement = {
  id: function() {
    if($scope.dada || $scope.lala) {
      return $scope.dada
    }

    return $scope.haha
  }
}

The variables are nonsense but pretend they're defined (they are in my circumstance, this is just an example).

And then in the HTML with Angular directives I have an input like so:

<input type="text" ng-model="requirement.id" placeholder="ID">

The value returned from the function is not the value of requirement.id. How can I pass a function like above but have Angular.js evaluate the function and use the returned value?

Edit:

I tried this which didn't work:

$scope.requirement = {
  id: null
}

if($scope.dada || $scope.lala) {
  $scope.requirement.id = $scope.haha;
}

When I run a console.log(requirement) the value is changed however it doesn't represent the new value in the view. The input in the view still shows null

Answers


If you are doing two way binding, you need to define id as a getter/setter function that has one argument. So when a value is passed it acts as a setter, updating the model. Otherwise it just gets the current value based on your logic.

$scope.requirement = {
  id: function(newId) {
    if (arguments.length) {
       $scope.dada = newId;
    }
    return ($scope.dada || $scope.lala) ? $scope.dada : $scope.haha;
  }
}

You have to update your input element and add ng-model-options attribute.

<input type="text" ng-model="requirement.id" ng-model-options="{ getterSetter: true }" />

If you're just talking about one way binding, then you don't need to use the getter/setter or ng-model.

<input type="text" value="{{requirement.id()}}" readonly />

ng-model is two-way binding and the way you defined it requirement.id returns a function object (it does not execute the function), but even more, it will overwrite that object when people fill in your input field, because you told Angular to put the value of the input box into the requirement.id variable. If you only need to get the value, use {{requirement.id()}} or even more readable {{requirement.getId()}}.

If you do really need two-way binding with a function go for Daniel's solution.


Need Your Help

PDF file is loaded into CGPDFDocumentRef, but it doesn't display in view

cocoa-touch pdf cgpdfdocument cgpdf

I would like to use CGPDF API to show and manipulate the PDF on IPAD, but firstly, I'm trying to just show PDF on my view from the easy way (without screen adjusts). I don't know why PDF doesn't ap...