3

I am passing user input to a controller function but empty strings do not declare object properties.

<form>
  <input type="text" ng-model="data.location" />
  <input type="text" ng-model="data.radius" />
  <button  type="button" ng-click="getSearch(data)">Search</button>
</form>

$scope.getSearch = function(data) {
  console.log(data);
  //undefined
  //...but what if I want {location:'', radius:''}
};

Is there a way to force the object properties to be created when passing empty strings on the fly?

2 Answers 2

4

You should be able to initialize data.location and data.radius in your controller to '', at least that way they aren't undefined.

Sign up to request clarification or add additional context in comments.

3 Comments

Sure, but is this the only way? There's no way to force it on the fly?
@DanKanze no otherwise object will be initialized only when you edit the text box
ng-init={data: {location: '', radius: ''}" would do the trick, but its same like in controller
3

You should access it as $scope.data and not just data.

Also you don't need to pass it as argument to your getSearch(). models are bound to $scope and should be accessed via $scope

1 Comment

Thanks for this that makes more sence then what I was doing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.