5

How can I direct AngularJS to assimilate the value attribute into the model? Any field that I give an ng-model attribute has its value immediately replaced with nothing, or whatever I define in the controller. Here's some code:

<form action="" method="post" ng-controller="PageCtrl">
    <input type="text" name="title" ng-model="title" value="Initial field value">
</form>

And the Javascript...

function PageCtrl($scope, Slug) {
    $scope.title = null;
}

I've tried not setting$scope.title, setting it to other things, but no matter what I do, the value is completely ignored. What can I do?

1 Answer 1

5

Yes, the value attribute is ignored by angularjs in favor of ng-model. It'd better just to remove value from your input entirely to avoid confusion.

The angular way of setting the default value would be to set $scope.title = 'Initial field value' inside your controller, and that's the preferable way to structure things as far as possible. If that's not possible then you can use ng-init on the input to do the same thing too, e.g.

 <input type="text" name="title" ng-model="title" ng-init="title = 'Initial field value'">
Sign up to request clarification or add additional context in comments.

5 Comments

In this case, I'm building a form with Rails. How would you recommend getting that data to the controller for form population?
@Jonah I'm not sure what the problem is? You can set the $scope.title="some default value" or you can set a placeholder attribute on the input. What are you actually trying to achieve? You should be able to use either $http or $resource to communicate with the service layer.
@shaunhusain I want to be able to dynamically populate the form without any Javascript. Seems like this ought to be basic functionality :(
@Jonah it is basic functionality, but the way to do it is to make an http call with the $http service inside your controller. Your angular app should interact with your ruby backend via http calls, not by having rails dynamically return different views.
One of the main points of having angular over ember was the ability to apply it to parts of the system, instead of doing a single page app from scratch - so you could still render a new page with form from server including model data in values, and update model via $http with angular. Now it seems like you need to render dumb form and make additional request for default/existing object data. Besides that you loose the fall back to regular form POST action. So bad..

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.