Clearing a text entry field after processing the input - angularjs

Having completed CodeSchool's AngularJS course, I'm trying to go back through and use what I've learned to build a simple to-do app. I've gotten it to the point where I can add entries to a list, but I'm not able to clear the text entry field after I've used the input. Here's my JSFiddle.
Specifically, here's my addComment() function:
card.addComment = function(newComment) {
card.comments.push(newComment.text);
newComment = {text: ""};
};
And the corresponding Angular HTML:
<form ng-submit="card.addComment(newComment)">
<input name="comment" placeholder="Add comment" ng-model="newComment.text">
</form>
At first I was passing the data in as a string (<input ng-model="newComment"> instead of newComment.text), but then I remembered that strings get passed by value, not by reference. I figured newComment was being blanked in the function but not passed back through Angular to the document. But even after I changed newComment to an object so it would be passed by reference, it made no difference--clearing the value in JavaScript has no effect on the page. What am I doing wrong?

I remembered that strings get passed by value, not by reference.
This line of reasoning is incorrect. Everything in JavaScript gets passed by object reference. See this question: Is JavaScript a pass-by-reference or pass-by-value language?
Replacing the raw string with an object does potentially buy you some affordance, though. However, whether or not it's a string or an object (and indeed, a string is an object!), newComment = someValue will never work.
Instead, you'll need to set the text property on the object. This doesn't create a new object, it just modifies a property, so the reference is preserved. Try this instead:
newComment.text = '';

Try this:
card.addComment = function(newComment) {
card.comments.push(newComment.text);
newComment.text = "";
};
What you're doing is creating a new object on the scope and breaking the binding which was set up on the original object. By updating the text property only, you leave the binding intact and achieve your goal of clearing the input field to which it is bound.

You can rest a form which may do what you require
document.getElementById("myForm").reset();

Related

How to call angularjs function while adding data to a json array?

As I have mentioned in this question, I have a function that returns a different text based on an input.
This is working fine when I use it in static text areas, like below:
<td>{{('input_text'|fnName:dataObject:'query_param')}}</td>
How can I call this function while I am assigning data to a json object? Originally the input_text is added to the json, but I need to run a lookup and replace the text.
EDIT: The json object is assigned to a dropdown, but I doubt if I will be able to call my function in the dropdown attributes.
p.s. The content in dataObject could change while using the application; so the function should be invoked with the latest data.
Try setting the filter's $stateful property to true.
https://stackoverflow.com/a/35563980/4028303
This should make the filter re-run upon digest cycles, even if the left-side data being passed in hasn't changed.

Set model value programmatically in Angular.js

I'm an author of angular-input-modified directive.
This directive is used to track model's value and allows to check whether the value was modified and also provides reset() function to change value back to the initial state.
Right now, model's initial value is stored in the ngModelController.masterValue property and ngModelController.reset() function is provided. Please see the implementation.
I'm using the following statement: eval('$scope.' + modelPath + ' = modelCtrl.masterValue;'); in order to revert value back to it's initial state. modelPath here is actually a value of ng-model attribute. This was developed a way back and I don't like this approach, cause ng-model value can be a complex one and also nested scopes will break this functionality.
What is the best way to refactor this statement? How do I update model's value directly through the ngModel controller's interface?
The best solution I've found so far is to use the $parse service in order to parse the Angular's expression in the ng-model attribute and retrieve the setter function for it. Then we can change the model's value by calling this setter function with a new value.
Example:
function reset () {
var modelValueSetter = $parse(attrs.ngModel).assign;
modelValueSetter($scope, 'Some new value');
}
This works much more reliably than eval().
If you have a better idea please provide another answer or just comment this one. Thank you!
[previous answer]
I had trouble with this issue today, and I solved it by triggering and sort of hijacking the $parsers pipeline using a closure.
const hijack = {trigger: false; model: null};
modelCtrl.$parsers.push( val => {
if (hijack.trigger){
hijack.trigger = false;
return hijack.model;
}
else {
// .. do something else ...
})
Then for resetting the model you need to trigger the pipeline by changing the $viewValue with modelCtrl.$setViewValue('newViewValue').
const $setModelValue = function(model){
// trigger the hijack and pass along your new model
hijack.trigger = true;
hijack.model = model;
// assuming you have some logic in getViewValue to output a viewValue string
modelCtrl.$setViewValue( getViewValue(model) );
}
By using $setViewValue(), you will trigger the $parsers pipeline. The function I wrote in the first code block will then be executed with val = getViewValue(model), at which point it would try to parse it into something to use for your $modelValue according the logic in there. But at this point, the variable in the closure hijacks the parser and uses it to completely overwrite the current $modelValue.
At this point, val is not used in the $parser, but it will still be the actual value that is displayed in the DOM, so pick a nice one.
Let me know if this approach works for you.
[edit]
It seems that ngModel.$commitViewValue should trigger the $parsers pipeline as well, I tried quickly but couldn't get it to work.

how can I bind an input to a property deep within a complicated data structure?

I have an angular-rails resource with a property that consists of irregular data that is potentially quite complicated-- something like:
{ foo: [ { bar: 'baz', lol: [ { 'omg': ... etc
I built a directive which takes this data and drills down into it, dynamically rendering form fields for each object... I've got the data displaying perfectly, however the piece of the puzzle that's missing is, how can I take advantage of Angular's binding so that changing the value on the form input will actually update that attribute in the model?
Originally I was thinking this should be simple, as my code drills through the data structure, it can just be maintaining a path, so I'd end up with something like: 'myObject.foo.bar'
Then I could just pass that to the form input's ng-model attribute...... however, I could not get angular to recognize ng-model="path" where $scope.path = "myObject.foo.bar"... ng-model="{{path}}" did not work either.
My directive is using angular.forEach to drill down into this datastructure, and someone had mentioned to me that I should perhaps be using ng-repeat instead, but I wasn't sure if this is the correct way to go or not? I still feel like there should just be a way to do ng-model="path" and have that work...
Any guidance would be greatly appreciated.
To use dynamic property names, use array notation. I.e. myObject["foo"]["bar"]. Plunkr: http://plnkr.co/edit/W60F75?p=preview
Can you try setting an property on the scope with the value of the object itself and then refer it in the form element? Like below:
// In your script
$scope.obj = myObject;
// In your form
<input ng-model="obj.foo.bar" type="text" />

AngularJS: Set the model to be = {} again doesn't clear out input type='url'

I have a fiddler setup, when i click a reset button it should clear out the input controls, this seems to work but not when the input type='url'
Here is the fiddler
Is there an issue or something that I am not understanding.
When I set
$scope.myform = {};
This seems to clear out the other input type but the input type='url' isn't being cleared.
Anyone know why?
The issue you see happens when you don't have a valid value inside the input[type="url"]. An invalid value just stays in the view (the input field) and doesn't get pushed to the scope variable inside ng-model. The variable will be updated only when and if the value is correct.
You can test it by entering a valid value. The reset button will work. If you enter an invalid value it won't.
You can fix it by setting $scope.myform = null instead of $scope.myform = {}. This will empty the field because the scope variable (expression) will be undefined. It will be automatically created by Angular once you enter a valid value inside any of the fields.
Because you need to put a valid url in the 2nd box like http://www.abc.com, then the reset button will work.
In order to correctly update the view/model, I would suggest that you explicitly reset the model's properties like so:
$scope.reset = function() {
$scope.myform = {
foo: '',
bar: ''
};
$scope.formName.$setPristine();
};
Setting 'myform' to an empty object deletes its fields, it doesn't set them to a blank string. It's quite likely angular's cleanup may not be deleting the value the view is referencing, thus the confusion between the application's model and view states.
Hope it helped.

knockout checkbox binding selected value

I am learning knockout and was trying to build a page that will build a list of selectable users.
JSFiddle: http://jsfiddle.net/Just/XtzJk/3/ (I am unable to get the data assignment right).
The data assignment is working in my page as I make a call to Controller, like below and it binds to the controls as expected
$.getJSON("/Wizard/GetUsers",function(allData){
var mappedUsers = $.map(allData.AllUsers, function(item){return new User(item)});
self.AllUsers(mappedUsers);
if(allData.SelectedUsers != null){
var mappedSelectedUsers = $.map(allData.SelectedUsers, function(item){return new User(item)});
self.SelectedUsers(mappedSelectedUsers);}
});
Problems:
a.) What's wrong with the JSFiddle I wrote? Got it working.
b.) In my code I am able to get the function for selected checkbox invoked but I am unable to get the value stored in the "User" parameter that I receive in the function. In Chrome JS console I can see the user object has the right value stored, I just am unable to retrieve it. Got this by doing ko.toJS().
Thanks.
EDIT:
Ok, I got my JSFiddle working, I had to select Knockout.js in the framework. The updated fiddle: http://jsfiddle.net/Just/XtzJk/5/
Also, for getting the selected checkboxe's value I did
ko.toJS(user).userName
But I think I'll take the approach of selecting values from a list and then on click move them to another "Selected" list and remove the values from the previous ones. Got this idea from this post: KnockoutJS: How to add one observableArray to another?
OK, I think I've got the solution you need...
I started by setting up an observable array of selectedUserNames, and I applied this to the <li> elements like this:
<input type="checkbox"
name="checkedUser"
data-bind="value: userName, checked:$root.selectedUserNames" />
[Note: it's important to declare the value before declaring the checked binding, which threw me for a bit… ya learn something new every day!]
Why bind an array of userName values to the checked binding? Well, when an array is passed to the checked binding, KO will compare the value of each checkbox to the values in the checked array and check any checkbox where its value is in that array. (Probably explained better in the KO documentation)
Then, while I left the observableArray for SelectedUsers, I set up a manual subscription to populate it, like so:
self.selectedUserNames.subscribe(function(newValue) {
var newSelectedUserNames = newValue;
var newSelectedUsers = [];
ko.utils.arrayForEach(newSelectedUserNames, function(userName) {
var selectedUser = ko.utils.arrayFirst(self.AllUsers(), function(user) {
return (user.userName() === userName);
});
newSelectedUsers.push(selectedUser);
});
self.SelectedUsers(newSelectedUsers);
});
[I had originally tried to set up a dependent observable (ko.computed) for selectedUserNames with functions for both read and write, but the checkbox wasn't having it.]
This subscription function examines the new selectedUserNames array, looks up the user from AllUsers whose userName matches a value in that selectedUserNames array, and pushes matching User objects to the SelectedUsers array… well, actually it pushes each matching User to a temp array and then that temp array is assigned to SelectedUsers, but the goal is met. The SelectedUsers array will now always contain what we want it to contain.
Oh, I almost forgot… here's the fiddle I created, so you've got the full solution: http://jsfiddle.net/jimmym715/G2hxP/
Hope this helps, but let me know if you have any questions

Resources