How to make an Add/Remove Array of strings in AngularJS - javascript

I need to make a data binding to an array of strings.. I need an array of directions.
I module it this way:
JS
function ShoppingCartCtrl($scope) {
$scope.directions = ["a", "b", "c"];
$scope.addItem = function (item) {
$scope.directions.push(item);
$scope.item = "";
};
$scope.removeItem = function (index) {
$scope.directions.splice(index, 1);
};
}
HTML
<div ng-app>
<div ng-controller="ShoppingCartCtrl">
<br />
<table border="1">
<thead>
<tr>
<td>directions</td>
<td>Remove Item</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in directions">
<td>
<input ng-model="item" />{{$index}}
</td>
<td>
<input type="button" value="Remove" ng-click="removeItem($index)" />
</td>
</tr>
</tbody>
</table>
<br />
<table>
<tr>
<td>
<input type="text" ng-model="item" />
</td>
<td colspan="2">
<input type="Button" value="Add" ng-click="addItem(item)" />
</td>
</tr>
<tr>
<td>{{directions}}</td>
</tr>
</table>
</div>
</div>
Everything works as it was expected, but I have a bug that I can't find. When you try to modified the values directly from the inputs, you are not allow. You write and nothing happened (THIS WAS SOLVED WITH PUTTING THE LAST VERSION OF ANGULAR IN JSFIDDLE).
Continue: Now you can modify the values, but they are not updated in the model. If anyone can help me, it would be awesome!!
You can see it working in this jsfiddle

Solution #1: bind an object's property instead of a string
You shouldn't edit item directly, but instead update an attribute of item.
See a working example here: http://jsfiddle.net/ray3whm2/15/
If you want more information you should read this article: http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/
Basically, never bind a property by itself, instead always have a dot in your bindings, i.e. item.name instead of item. This is a restriction due to javascript itself and not angularjs.
Solution #2: manually update your model
If you really need to, you can actually keep your array up to date manually by using the ng-change directive. See a working example here: http://jsfiddle.net/ray3whm2/16/

There was a problem with older versions of Angular when binding to primitives. See this SO question
So first update the version to a newer version of Angular.
ng-repeat creates a child scope. Because your item in ng-repeat="item in directions" is a primitive (i.e. a string), <input ng-model="item"> modifies the child scope. That's why you won't see the changes in the parent.
One way to address it is to create an array of objects instead of strings for this to work properly:
$scope.directions = [{d: "a"}, {d: "b"}, {d: "c"}];
Then your <input> would be:
<input ng-model="item.d" />
(Another way, I thought, would be to use ng-model=directions[$index], but for some reason it would lose focus after every keypress.
UPDATE: #PSL showed that this could work if you add track by $index)

Related

ng-Show not updating inside ng-repeat

I have the following
<table id="socialMediaContainer" class="socialMediaContainer" style="width: 100%;">
<tbody>
<tr ng-repeat="row in detailCollection.ChannelsInfo"
ng-controller="WhiteLabelSitesCtrl">
<td><input id="txtSocialName" type="text" class="socialName"
placeholder="Name" ng-disabled="ViewMode" maxlength="250"
value="{{row.SocialChannelName}}" /> </td>
<td><input id="txtSocialURL" type="text" class="txtLabel socialURL"
placeholder="URL" ng-disabled="ViewMode" maxlength="250"
value="{{row.SocialChannelURL}}" />
</td>
<td class="DragnDropIcon"></td>
<td>
<a class="orange " ng-show="ViewMode">Upload</a></td>
</tr>
</tbody>
</table>
and I have another button outside the ng-repeat that updates the ViewMode variable, but this is not working inside the ng-repeat neither for the ng-show not the ng-disabled. what am i missing here?
The problem seems to be, that you need to move ngController directive to the table level (at least): it can't be on the same element with ngRepeat if the later iterated over the array defined in controller.
<table ng-controller="WhiteLabelSitesCtrl" ... >
<!-- ... -->
</table>
Demo: http://plnkr.co/edit/tu4TLmWIxdcYaiEd7whn?p=preview
ng-repeat creates a childscope for each item in the repeater.
Thus viewmode will be a primitive value on that child scope and therefore as a primitive will lose inheritance binding with the parent scope.
If you declare it as an object property in the controller scope however it will then be a reference to that parent object.
$scope.mode ={ViewMode: false}
html example
<a class="orange " ng-show="mode.ViewMode">Upload</a></td>
Try to pass object instead variable inside ng-repeat scope. Instead ViewMode,
declare in your controller:
$scope.model = {};
$scope.model.ViewMode = false;`.
And your binding must be like this: <a class="orange " ng-show="model.ViewMode">. After that all be work fine.
Read this article to understand why it happens: https://github.com/angular/angular.js/wiki/Understanding-Scopes
The button outside of the ng-repeat is not going to be nested in the same controller. The variable that it's modifying probably is not the same one that ViewMode under the WhiteLabelSitesCtrl is looking at.
When you point to this ng-controller, that controller will be activated with a new scope associated with it
<div ng-repeat ng-controller="WhiteLabelSitesCtrl">
<div ng-show="someValue"></div>
</div>
When you reference this controller again on another tag, it won't reference the existing controller as you might be expecting, it'll actually do the exact same thing... it will create the controller, and create a new scope for it- completely separate from the original one.
<div ng-controller="WhiteLabelSitesCtrl">
<button ng-click="someValue = !someValue"></button>
</div>

Update model based on ng-repeat of array

Sorry if you find this question's solution is simple or silly.
Need suggestions or solution on this angular part.
I have an object containing array("value"), as shown below.
scope.resp.DefaultData.graphRowData = [
{YName:"Mary", value:[1,4], points:1},
{YName:"Tom", value:[2,5], points:1}
];
My Code viewer uses this style to render the array.
<table>
<tbody>
<tr ng-repeat="rowLabels in resp.DefaultData.graphRowData track by $index">
<th>
<input type="text" value="{{rowLabels.YName}}" ng-model="rowLabels.YName"/>
</th>
<td ng-repeat="value in rowLabels.value track by $index">
<input type="text" ng-model="value"/>
</td>
</tr>
</tbody>
</table>
The html viewer would render like below way:
<table>
<tbody>
<th>Mary</th><td>1</td><td>4</td>
<th>Tom</th><td>2</td><td>5</td>
</tbody>
</table>
Now to my question:
The table displays the data as per the model but if i try to update the table with custom or edit the values, doesn't update the model and the value remains same
For example: Mary has two tags of 1 and 4 values, if I try to change the 1 to 2 and 4 to 5, the data inside the model remains same without update.
Is there any way to fix in my code or should I change the array into array of objects like below
value:[{val:1},{val:4}]
and so ... for other objects under resp.DefaultData.graphRowData? Then it would work fine. Just confused why for array not working in angular js in my code! :(
You need to pass a reference of array instead of value in ng-model
<tr ng-repeat="rowLabels in resp.DefaultData.graphRowData track by $index">
<th>
<input type="text" value="{{rowLabels.YName}}" ng-model="rowLabels.YName"/>
</th>
<td ng-repeat="value in rowLabels.value track by $index">
<input type="text" ng-model="rowLabels.value[$index]"/>
</td>
</tr>
check this working plunker

Why does this Javascript only run once per page?

I have this Try-it-Yourself section to my website but for some reason when I am wanting to have more than one Try-it-Yourself section it will only work for the one at the top of the page. So if I had three of them on a page the top one would work in the way I want but the next two would do nothing.
I have the following HTML:
<div class="tryit">
<table>
<tr>
<td>Try It Yourself</td>
</tr>
<tr>
<td><textarea id="input" rows="10" cols="47"></textarea></td>
</tr>
<tr>
<td><input onclick="update();" type="button" value="Update"></td>
</tr>
<tr>
<td><iframe id="output" name="output" width="600" height="300" ></iframe></td>
</tr>
</table>
</div>
And the following Javascript:
function update()
{
var tryitoutput = document.getElementById('input').value;
window.frames['output'].document.documentElement.innerHTML = tryitoutput;
}
Thank you.
As others mentioned, this is happening because there can't be more than one HTML element with same value of ID attribute. In your case javascript only finds the first element, that's why it doesn't work on later Update buttons. The simplest approach would be to set different ID attribute values for different "Try it yourself" boxes:
Slightly modify your JS, see following jsFiddle example
function update(tryItIndex) {
var tryItOutput = document.getElementById('input-' + tryItIndex).value;
window.frames['output-' + tryItIndex].document.documentElement.innerHTML = tryItOutput;
}
That's because you are referring to the textarea and the output by id which means it will always just retrieve the first one. A quick fix would be having unique id's for these fields and send the names as parameters to the update function like update(inputId, outputId)

AngularJS - Directives with Angular UI Bootstrap

I'm using Angular UI - Bootstrap, specifically the Typeahead directive. http://angular-ui.github.io/bootstrap/#/typeahead
I'm attempting to use the 'typeahead-template-url' to create custom html templates for my suggestion boxes. After trying multiple techniques, unsuccessfully, I discovered that by purposely messing up my quotation marks 'solved' the display issues. I would love to understand why this is breaking and get it working properly.
For example: this works
<table class="> <!--see class quote error -->
<tr>
<td>
<div ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)">
<a>ID{{ match.model.id }} - {{ match.model.text }}</a>
</div>
</td>
</tr>
</table>
This DOESN'T WORK
<table class="">
<tr>
<td>
<div ng-mouseenter="selectActive($index)" ng-click="selectMatch($index)">
<a>ID{{ match.model.id }} - {{ match.model.text }}</a>
</div>
</td>
</tr>
</table>
FIDDLE is here: http://jsfiddle.net/nicktest222/JXtaZ/24/
Additionally, when you select an item in the results list, it returns the entire object. How can I get it to return a specific property in the object?
Any help would be greatly appreciated.
Thanks
I think it is the way you add your template (columnTwo.html) in JSFiddle.
Look at my demo (which is based on yours): http://jsbin.com/aMOrOra/1/edit?html,js,output
As for the typeahead property:
<input type="text" ng-model="monkey" typeahead-template-url="columnTwo.html" typeahead="suggestion as suggestion.text for suggestion in sample_data | filter: $viewValue" />
Here it means that the suggestion object is used as the selected value, but I want to display only the suggestion.text property in the box. But monkey will still be set to the selected suggestion object.
Just so you know, your current filter will look for the query on every properties of the suggestion object, not only text.
EDIT: To filter only the text property, use the filter like this:
filter:{'text':$viewValue}

How to make changes to $data propagate back to Knockout's view-model?

I've got the following code using Knockout.js to display an array of bools as a series of checkboxes:
<table>
<tr data-bind="foreach: Array">
<td><input type=checkbox data-bind="checked:$data"></td>
</tr>
<tr data-bind="foreach: Array">
<td data-bind="text:$data"></td>
</tr>
</table>
<button data-bind="click: toggle0">Toggle Element 0</button>
<script>
var simpleModel = {
"Array" : ko.observableArray([ko.observable(false),
ko.observable(false),
ko.observable(true)]),
"toggle0" : function() {
simpleModel.Array()[0](!simpleModel.Array()[0]());
}
};
ko.applyBindings(simpleModel);
</script>
If you look at http://jsfiddle.net/tP9Dm/3/, you can see that, while the checkboxes respond to changes in the view-model, the view-model doesn't respond to changes in the checkboxes.
According to https://groups.google.com/d/msg/knockoutjs/-dHpOg5ZBPI/1q4iqdTlKvUJ, it looks like $data is unwrapped by the foreach loop, so data-bind doesn't know to use it to update the model.
Clearly I can fix this by making the array contain objects instead of simple booleans, but that seems like it should be an unnecessary extra layer of indirection. Is there a simpler way to propagate changes back to the model?
There doesn't seem to be a way to do this, because $data in this case is the unwrapped value.
Even setting up a click handler doesn't work, because the data sent to your handler is also unwrapped.
Bummer. Looks like the only way to do this is to wrap your observable into an object, another layer of indirection.

Categories