Binding and Creating scope variables dinamically in AngularJS - javascript

Context: I am building a helper with dynamically editable help sections (each one with its title and content). I have an "Add" button at the bottom of the last help existing section to add more help sections to this helper.
I am binding a variable $scope.helpVisible to set the visibility of the section to ReadOnly or Editable with ng-show and ng-hide.
Problem: When I click on "Add" to add a new help section to the helper, I need a new variable to set the visibility of this new element (a div). The problem is that it takes the previous variable to decide the visibility of this new element.
I have tried to create a list $scope.listOfVilibilities pushing a new item every time I create a new help section.
How can I create new variables in the scope "on the fly" and bind them in the view?

Try creating objects into a array and use ngRepeat directive to add this new object into view.
for example controller:
function MyCtrl($scope) {
$scope.list = [];
$scope.add = function(){
$scope.list.push({value:void(0), disabled: false});
}
$scope.delete = function(value){
$scope.list = _.remove($scope.list, function(n){
return n.value !== value;
});
}
}
Important! I used lodash library in the delete function. Doc. here
The HTML look like this:
<div ng-controller="MyCtrl">
<button ng-click="add()">
Add
</button>
<ul>
<li ng-repeat="some in list">
<input ng-model="some.value" ng-disabled="some.disabled"/>
<button ng-click="some.disabled = !some.disabled">
{{!some.disabled}}
</button>
<button ng-click="delete(some.value)">
Delete
</button>
</li>
</ul>
</div>
Take a look to this example live in jsfiddle.

Related

storing specific element in knockout.js viewmodel (array)

I want to parse specific element from an existing viewModel and put it into a new array.
I have an applications viewModel which has tons of information of applicants. It is called in the following way:
self.applications = ko.observableArray(#Html.Json(Model.ApplicationCompatibilities.Select(o => o.JsonForm)) || []);
So the "application" object has several elements in it as shown in the attached image above.
What I wanted to do was, I wanted to retrieve only the "applicationKey" element into a new array. So what I did was :
self.previewApplication = ko.computed(function () {
return ko.utils.arrayFilter(self.applications(), function (i) {
return i.application.applicationKey;
});
});
I intended to loop through the "self.applications()" viewModel and return only the "application.applicationKey". But what I actually get by doing that is:
I am just getting the same "applications" object inside the new viewModel.
How can I get an array of only the "application.applicationKey" ?
Thanks! Please Help!
EDIT:
This works now! Now my viewModel.previewApplication() gives me a list of applicationKey's. Now what I want to do is, I want to add a link that loads a modal. And inside that modal I want to display the specific "application" that has a specific "applicationKey"
For example, the link to the modal will look like this:
<a href="#" data-toggle="modal" data-target="#previewApplicantModal" data-bind="attr: { 'data-applicationKey': application.applicationKey }">
Preview Application
</a>
So If I inspect the element of the link, it has a new data-binding:
<a href="#" data-toggle="modal" data-target="#previewApplicantModal" data-bind="attr: { 'data-applicationKey': application.applicationKey }" data-applicationkey="abc976cfx">
Preview Application
</a>
Finally I want to loop through the "application" object and return only "one" element of the object that has "abc976cfx" as its applicationKey.
Is there an easy way of doing this? I attached a screenshot for better explanation.
arrayFilter filters the array and the function returns true or false if the item matches your filter criteria or not. You want arrayMap instead.

Dynamically creating buttons for paragraphs with Angularjs

I want to dynamically create a button for each paragraph that is created inside a contenteditable div. I've been thinking a lot and can't come up with a good solution. The things I've thought about are
putting the button and paragraph together into one directive and have the content editable add a new <button+p> tag each time the user hits return. This has the benefit of having both the button and the paragraph use the same controller, but it leaves the button in the content editable div so it can be deleted...
Use the Model to maintain an array of all paragraphs in the div, then create buttons for each of the paragraphs in this array. My question here is: if I update the model with new paragraphs, will the buttons automatically be generated? If I use ng-repeat?
I'm kind of at a loss of the best way to approach this. Should I try to build the button and the paragraph together? Or is there a better way of separating them but binding them together so that when the button is clicked I can change the styling of the paragraph?
Create a directive and associate it to your div.
Ex:
Define as binding a parameter with two way data binding, the ones that will keep track of the p elements created inside the div and that will be passed from the the controller associated to your view.
Inject inside your link function of the directive the $element.
Then bind to the div with contenteditable the input event in order to detect edits in the div.
Inside this code get the total number of p children of your div, and associate it to the variable allowed from the directive.
In this way your parameter is always sync with the number of p inside your div, and it can be accessed from outside scopes because you pass it from outside.
Then inside your view, use a ng-repeat iterating over this parameter you passed in the directive, and create your dynamic content inside the ng-repeat.
HTML Code:
<div ng-app="myApp">
<div ng-controller="Controller">
<div contenteditable="true" p-inspector p-elements="pElementsNumber">
TEST
</div>
{{pElementsNumber}}
<div ng-repeat="p in returnArrayFromNumber() track by $index">
P detected
</div>
</div>
</div>
Here the JS code:
angular.module('myApp', [])
.controller('Controller', ['$scope', function($scope) {
$scope.pElementsNumber = 0;
$scope.returnArrayFromNumber = function () {
return new Array($scope.pElementsNumber);
};
}])
.directive('pInspector', function($rootScope) {
return {
restrict: 'A',
scope: {
pElements: '='
},
link: function ($scope, $element, $attrs) {
$element.on("input", function(e) {
var htmlString = $element.text();
var regex = /<p>[^<p><\/p>]*<\/p>/gi, result, count = 0;
var count = 0;
while ( (result = regex.exec(htmlString)) ) {
count++;
}
$scope.pElements = count;
$rootScope.$apply();
});
}
};
});
Here the running example: https://jsfiddle.net/a0jwmpy4/81/
Just one recommendation: if you want to detect more elements, make this directive dynamic accepting the name of the elements in the parameters and detecting all of them. Please do not create a single directive for every element you want to detect inside the div :)
Hope this helps
Have you tried to use ng-repeat for each paragraph/modal then set all your code in each repeat something like below
<div>
<p ng-repeat="paragraph in paragraphs"> {{contentsOfParagraph}} <button ng-click="editParagraph(MayBeIDOfParagraph)">Edit</button></p>
</div>
now your js code will have a function editParagraph that pass the ParagraphID

AngularJS on top of server generated content

I'm looking for a way to integrate something like ng-repeat with static content. That is, to send static divs and to have them bound to JS array (or rather, to have an array constructed from content and then bound to it).
I realize that I could send static content, then remove and regenerate the dynamic bits. I'd like not to write the same divs twice though.
The goal is not only to cater for search engines and people without js, but to strike a healthy balance between static websites and single page applications.
I'm not sure this is exactly what you meant, but it was interesting enough to try.
Basically what this directive does is create an item for each of its children by collecting the properties that were bound with ng-bind. And after it's done that it leaves just the first child as a template for ng-repeat.
Directive:
var app = angular.module('myApp', []);
app.directive('unrepeat', function($parse) {
return {
compile : function (element, attrs) {
/* get name of array and item from unrepeat-attribute */
var arrays = $parse(attrs.unrepeat)();
angular.forEach(arrays, function(v,i){
this[i] = [];
/* get items from divs */
angular.forEach(element.children(), function(el){
var item = {}
/* find the bound properties, and put text values on item */
$(el).find('[ng-bind^="'+v+'."]').each(function(){
var prop = $(this).attr('ng-bind').split('.');
/* ignoring for the moment complex properties like item.prop.subprop */
item[prop[1]] = $(this).text();
});
this[i].push(item);
});
});
/* remove all children except first */
$(element).children(':gt(0)').remove()
/* add array to scope in postLink, when we have a scope to add it to*/
return function postLink(scope) {
angular.forEach(arrays, function(v,i){
scope[i] = this[i];
});
}
}
};
});
Usage example:
<div ng-app="myApp" >
<div unrepeat="{list:'item'}" >
<div ng-repeat="item in list">
<span ng-bind="item.name">foo</span>
<span ng-bind="item.value">bar</span>
</div>
<div ng-repeat="item in list">
<span ng-bind="item.name">spam</span>
<span ng-bind="item.value">eggs</span>
</div>
<div ng-repeat="item in list">
<span ng-bind="item.name">cookies</span>
<span ng-bind="item.value">milk</span>
</div>
</div>
<button ng-click="list.push({name:'piep', value:'bla'})">Add</button>
</div>
Presumable those repeated divs are created in a loop by PHP or some other backend application, hence why I put ng-repeat in all of them.
http://jsfiddle.net/LvjyZ/
(Note that there is some superfluous use of $(), because I didn't load jQuery and Angular in the right order, and the .find on angular's jqLite lacks some features.)
You really have only one choice for this:
Render differently for search engines on the server, using something like the approach described here
The problem is you would need to basically rewrite all the directives to support loading their data from DOM, and then loading their templates somehow without having them show up in the DOM as well.
As an alternative, you could investigate using React instead of Angular, which (at least according to their website) could be used to render things directly on the web server without using a heavy setup like phantomjs.

how to replace current repeater in angular

I init a repeater colorSetOne in the HTML, and then, I want to replace with another repeater colorSetTwo, how to do this (it can be trigger by an event)? and here is jsfiddle : http://jsfiddle.net/8xWRm/
HTML:
<ul ng-app ng-controller="cubeCtrl">
<li ng-repeat="color in colorSetOne">{{color}}</li>
Javascipt:
function cubeCtrl($scope){
$scope.colorSetOne = ["red","blue","green","oringe"]
$scope.colorSetTwo = ["blue","red","black","white"]
}
You just need to reassign colorSetOne
$scope.colorSetOne = $scope.colorSetTwo;
If you want to keep colorSetOne then you should put your repeater on another variable like colorSet and just assign the appropriate color set as needed.

How do I update my html on Click in Angularjs Controllers

I have the html Structure that I need to update from the json data. My Json data is in a Controller. I need to write an expression for ng-click event that will read the json data and put the in the corresponding div in html. but I am not sure how to acheive this.
Below is what I have so far.
<body data-ng-app>
<div class="container" data-ng-controller="UpdateDataCtrl">
<div class="inner1"></div>
<div class="inner2"></div>
</div>
UPdate Controllers
</body>
function UpdateDataCtrl($scope) {
$scope.data = [
{
"USA":"Eglish",
"Pop":"232423432432"
},
{
"France":"French",
"Pop":"1212323432"
},
{
"Spain":"Spainish",
"Pop":"3432432"
}
]
}
On each click the 2 Div should get updated from the json. First div should have USA---English Pop---2342234232 and then on next click the div should have data from France and so on.
http://jsfiddle.net/MBFpD/1/
Thanks
It appears that you are unclear on the concept of AngularjS. You don't want to update the DIVs. You want to reference your model and then change the data in your model.
For example you can write the div like this:
<div class="inner1">Population: {{data[dataindex].Pop}}</div>
Then in the Controller you initialize the dataindex to 0, so that this will output the population from the first entry in the array:
$scope.dataindex = 0;
The click function (you must have the link with the ng:click inside the block governed by the Controller!) could then just increase the dataindex by one and by using modulo restart at 0 again when the end of the array was reached.
$scope.click = function() {
$scope.dataindex = ($scope.dataindex+1) % $scope.data.length;
Here is an updated and modified jsfiddle of your example which will show everything in action: http://jsfiddle.net/MBFpD/2/
Bind your data to your scope when you click on the link:
$scope.update = function() {
$scope.data = data; //your array defined locally to the scope
};
ng-repeat your data bound to the scope; display the container if the size of the array is > 0.
Use {{index}} to get the iteration variable inside the loop.
Above all, move your ng-controller declarative at the top to enclose both your ng-repeat and your ng-click; otherwise, AngularJS cannot guess what you want to achieve.
http://jsfiddle.net/MBFpD/5/

Categories

Resources