angularjs value on load incorrect - angularjs

See this plunk
I want to use an object model on an input (for interaction with the angularui bootstrap typeahead). It works perfectly when selecting something from the typeahead, but on load it displays [object Object] How can I get the input to display a property of the model object on load?

Just in case someone else landed here just like me, having a [object Object] being displayed in some input(s)...
In my case, I named the form element with the same name of the model property, like this:
<form name="contact">
<input type="text" ng-model="contact.name" />
<input type="text" ng-model="contact.email" />
</form>
Either change the form name to a different name, or change the model name.
As Angular populates the $scope with a property with the same name as the form, it overrides the model instance!

I came across this also and docs don't show how to hook into bootstrap updater callback.
I did it by setting initial value to string. When you type in the field model will be a string. When you select from dropdown it will be object
app.controller('MainCtrl', function($scope) {
$scope.data = [{id:1,name:"google"}, {id:2, name:"microsoft"}];
$scope.selected = '';
$scope.$watch('selected',function(newVal,oldVal){
if(newVal && angular.isObject($scope.selected)){
console.log($scope.selected)
}
})
});
Plunker
Perhaps ther is a better way using directive's attributes but not sure what that is

Turns out there is currently a bug in ui-bootstrap that is fixed in master and will be out soon. I also misunderstood the ui-bootstrap build files and was including both the templated and the non-templated versions in my app.
I monkey patched my ui-bootstrap and switched to templated only and it is now working for me.
see the google group discussion

Angularjs Form showing [object Object] on load in form fields
It occurs only if your form name and ng-model name (value) are same

Related

AngularJS: Why I can't print a model variable directly (instead of using $modelValue property)?

In my view I have this form:
<form name="form1">
<input name="msg" id="msg" ng-model="form_data.msg">
</form>
In my controller I get the content of the input by
var message= $scope.form1.msg;
however when I insert some text (e.g. "test_abc") and try to print the contentof the input (within the controller), I get an object instead of the actual value. In fact
console.log(messageToSend);
gives this output
[DEBUG] message >>: [object Object]
controllers.js:646 Object {$viewValue: "test_abc", $modelValue: "test_abc", $$rawModelValue: "test_abc", $validators: Object, $asyncValidators: Object…}
Of course I can just get $modelValue, but I noticed that (sometimes) I can work with the model value (just by using $scope.modelVarName) it instead of printing it.
Sorry if this is quite vague but I can't find a concrete example right now.
However, just to sum up, I need to understand: is there a way (other than using .$modelValue property) to retrieve (within the controller) a model variable defined (in a form within a view)?
<input name=msg ng-model="form_data.msg"> with this markup the value of the input will be updated in the controller scope's form_data.msg property. [form_data is an object].
Angular will update the validation related info of the input field in form1.msg of controller's scope. Here form1 is the name of the form and msg is the name of the message. This is not the actual model. Your actual model is form_data.msg. form1.msg will contain the validation related information.
If you want to print the model use form_data.msg not form1.msg
I use your code in jsfiddle and it worked, with a little changes, I just define app and use
{{form1.msg}}
to print the value.
Here's the jsfiddle:
http://jsfiddle.net/diegounanue/5bbkmk3m/

angular "query" property : where is it defined?

AngularJS noob here.
I'm going thru the tutorial (https://docs.angularjs.org/tutorial/step_03) and see this in the example index.html template:
Search: <input ng-model="query">
I don't see any mention of a 'query' property in the accompanying JS files (controllers.js, etc).
Is query a property of the $scope object? If so is there a documentation for it? Can't seem to find one.
Thanks!
In this example query is not used in the JavaScript at all, so it isn't mentioned there.
It is created by <input ng-model="query"> and later used by the filter in phone in phones | filter:query.
With this html Angular watches for changes to query from typing into <input> and then reapplies the ng-repeat passing the new query value to filter.

AngularJS - Reset form using $setPristine() when all controls are emptied

I'm trying to create a reusable directive that will simply reset my form and it's child controls to pristine using the $setPristine() method IF all the form's input controls are emptied after the user has previously interacted with them and marked them dirty.
So basically the directive would monitor all the form <input> elements and if it determines all elements are empty call $setPristine() to reset everything back to square one.
This seems kind of trivial and something I could bust out with jQuery in 5 mins but I'm just getting my feet wet with Angular and I've been stumbling around this for a couple of hours struggling with the best approach so any help or guidance is greatly appreciated!
Edit, easier answer: Use the require or ng-require attribute on the form elements, keeping the form $pristine if there is an error.
If require is not wanted:
Note - you need angular version 1.1.x for $setPristine().
Assuming all of the ng-model's in the form are properties of the same object, you could $watch the object, loop through the properties to see if they are undefined or '' empty strings, and $setPristine() if they are.
Form HTML - all of the models are properties of input object:
<form name="form">
<input type="text" name="one" ng-model="input.one">
<input type="text" name="two" ng-model="input.two"><br/>
<input type="submit" ng-disabled="form.$pristine">
</form>
In the controller or directive, $watch the model for changes, then loop through the object, seeing if all properties are undefined or ''. (If used in the link function, you would typically use scope in place of $scope.
var setPristine = function(input){
if (input === undefined || input === ''){
return 0;
}
return 1;
}
$scope.$watch('input', function(i){
var flag = 0;
//loop through the model properties
for (var obj in i){
flag +=setPristine(i[obj]);
}
// if nothing in the model object, setPristine()
if(flag===0){
$scope.form.$setPristine();
}
}, true)// true allows $watch of object properties, with some overhead
Use the dirty/pristine states of the form to know if user has touched them, and a ng-pattern to know if the field is empty or not with a regexp like /.+/. Then you can just check myForm.$dirty and myForm.$error.pattern and voila!

How to get the NgModelController for input fields inside a ngRepeat directive?

Normally, with a form and input fields, the form controller is published into the related scope under the form name attribute. And, the NgModelController is published under the input name attribute.
So for an input field with an ngModel directive, the NgModelController for the input field can be retrieved like $scope.myFormName.myInputFieldName
The question is how to do the same thing (get the NgModelController) for input fields inside the ngRepeat directive?
I would like to name the input fields using $index as part of the name so each template instance is uniquely named. This renders OK, so
<input name="foo_{{$index}}" ...
renders the instance with $index == 3 to
<input name="foo_3" ...
But trying to get the ngModelController via the published names does not work (it's undefined), e.g.:
$scope.myFormName.foo_3
A plunker showing this is here: http://plnkr.co/edit/jYDhZfgC3Ud0fXUuP7To?p=preview
It shows successfully getting the ngModelController for a 'plain' input element and calling $setValidity, and also shows failing to get the ngModelController for an input element inside an ngRepeat directive.
Copied the relevant section of code from the plunker below:
<div ng-repeat="element in elements">
<div ng-class="{error: form['foo_{{$index}}'].$invalid}">
<input name="foo_{{$index}}" ng-model="element.a" type="number">
<span ng-show="form['foo_{{$index}}'].$error.bar">ngRepeat bar invalid</span>
</div>
</div>
{{form.foo_0.$setValidity('bar', false)}}
#Flek is correct that the new child scopes that ng-repeat creates are the root of the problem here. Since browsers do not allow nesting of <form> elements, ngForm must be used when nesting forms, or when you want to do form validation inside ngRepeat.
See Pawel's answer on the google group thread, which shows how to use ng-form to create inner forms, and/or #blesh's SO answer.
If i understand your question correctly, you are trying to have access to the form elements created inside the ng-repeat.
Please have a look at this fiddle http://jsfiddle.net/EF5Jp/. Inside the button click handler you will have the access to the element with id myForm.foo_2. You can notice that the element is retrieved by myForm.foo_2 and not $scope.myForm.foo_2. Second thing is, changing the value using its scope and not using its value property like angular.element(element).scope().foo = 6;.

AngularJS binding json to a form input

I can easily bind data to a div or pre tag with the code:
<div id="json_route{{route.id}}" ng-bind="items.route{{route.id}} | json"></div>
However, I want to try and bind this data to a hidden form input, I tried:
<input type="hidden" name="json_route{{ route.id }}"
ng-model="items.route{{route.id}} | json" />
Which returns me an error of:
Error: Non-assignable model expression: items.route2 | json (<input type="hidden" name="json_route2" ng-model="items.route2 | json">)
So obviously I cannot use | json when using ng-model. The angular docs are still a bit sparse and I can't seem to find how to assign this correctly, even if I can? Thanks :)
I need to get this json data loaded into my pyramid application, and assigning it into a hidden form field seemed the best way todo it, or should I be doing this in a different way?
"To be able to render the model into the view, the model has to be able to be referenced from the scope." (src: Angular Guide).
Angular needs to be able to reference the value in your ngModel expression to a $scope variable in your controller.
With ng-bind it worked, because ng-bind is not the same as ng-model. ngBind simply takes your expression and evaluates it inside the current scope and than replaces the text of the host element with the result. As Guide tells us, the value of ng-model must be an assignable angular expression to data-bind to.
To have your hidden input contain the json string representation of your 'items.route2' model you could setup a $watch expression in your controller which would "prepare" the json string of your model whenever it changes. See plnkr example.
Try using ng-init:
<input type="hidden" name="..." ng-model="items.route{{route.id}}"
ng-init="items.route{{route.id}} = data_from_server_here">
See also https://stackoverflow.com/a/12657601/215945.

Resources