ng-show nested in ng-repeat won't update - javascript

I've looked all over SO and Google and seen a whole bunch of reasons why ng-show wouldn't work inside of ng-repeat (scope issues, binding issues, etc.) but I can't quite pin down why mine isn't working. I was hoping that an extra pair of eyes could help me out. I'm very new to Angular, so hopefully my code makes some sense.
The goal: when $scope.current_set changes, the visible lmf-optionset changes. Currently, only the first optionset loads via Decision_Tree:loaded, and then when I try to load the next one via clickbox:clicked, $scope.current_set changes, but the view won't update.
JS
angular.module('lmf.option_set', [])
.controller('OptionsetCtrl', ['$scope', 'Optionsets', 'Decision_Tree',
function($scope, Optionsets, Decision_Tree) {
$scope.Optionsets = Optionsets;
$scope.current_set = {
name: null
};
$scope.$on('clickbox:clicked', function() {
$scope.current_set = Decision_Tree.get_next_optionset();
});
$scope.$on('Decision_Tree:loaded', function() {
$scope.current_set = Decision_Tree.get_next_optionset();
});
}
])
HTML
<div ng-controller='OptionsetCtrl'>
<div ng-repeat='set in Optionsets.option_sets'>
<div ng-show="set.name == current_set.name" lmf-optionset="{{set.name}}"></div>
</div>
</div>

Apparently lmf-optionset creates an isolated scope for each entry. These child scopes have link to parent's current_set, but they doesn't maintain a two-way binding. So when you are replacing the current_set value in you event handlers, child scopes are unaware that current_set was changed, and they are still referring to the old value.
You can either rewrite your event handlers like this:
$scope.current_set.name = Decision_Tree.get_next_optionset().name;
Or you can use controller as construction like this:
<div ng-controller='OptionsetCtrl as vm'>
<div ng-repeat='set in Optionsets.option_sets'>
<div ng-show="set.name == vm.current_set.name" lmf-optionset="{{set.name}}"></div>
</div>
</div>

Related

Knockoutjs - With bindings and state

I'm having an issue with component binding and state.
This is my html template:
<div class="ts-panel content">
<!--ko with: states.createState-->
<div data-bind="component: 'customer-create'">Testing CreateState</div>
<!--/ko-->
<!--ko with: states.lookupState-->
<div data-bind="component: 'customer-search'">Testing LookupState</div>
<!--/ko-->
</div>
This is my javascript
var myDataModel = function () {
var self = this;
self.states = {};
self.states.createState = ko.observable(true);
self.states.lookupState = ko.observable(false);
self.states.currentState = ko.observable(self.states.createState);
self.states.changeState = function (state) {
var currentState = self.states.currentState();
currentState(false);
self.states.currentState(state);
state(true);
}
};
return myDataModel;
I'm using another script to control which state I'm in by binding click events to certain buttons.
The problem I'm running into is that when I change the current state, the component bindings reset the state of the component. Eg. on the customer-create component, I fill out a form, then change to the lookupState, then change back to the createState, the form values are gone.
I think this is happening because the components are getting wiped out and recreated every time.
I also think that one solution to this is to store everything at the root level (i.e. the component that stores the states) and pass that all down when required to the individual components. However, I'd really like to keep the component-specific information inside those components.
Is there a way to store the state of the components or maybe store the components in a variable and bind to it that way?
From the documentations:
If the expression you supply involves any observable values, the expression will be re-evaluated whenever any of those observables change. The descendant elements will be cleared out, and a new copy of the markup will be added to your document and bound in the context of the new value.
The behaviour is same for the if binding as well. You could use the visible binding for this. This just hides and shows the div without actually removing it from the DOM. There is no containerless control flow syntax for visible. So, you'd have to add it to the div
<div data-bind="component:'customer-create', visible: states.createState">Testing CreateState</div>

AngularJS: Share data between different controllers

I have the following structures
<div ng-controller='ctrlA'>
<button ng-click='updateFactoryData(data)'></button>
<custom-dir>Custom directive with ctrlB</custom-dir>
<custom-dir>Custom directive with ctrlB</custom-dir>
<custom-dir>Custom directive with ctrlB</custom-dir>
...
<other-custom-dir>Custom directive with ctrlC</other-custom-dir>
<other-custom-dir>Custom directive with ctrlC</other-custom-dir>
<other-custom-dir>Custom directive with ctrlC</other-custom-dir>
...
</div>
I have a dataFactory, which when user clicks the button, the updated data will store in dataFactory, the dataFactory is injected to both ctrlB and ctrlC.
The problem is, when data is updated after clicking the button, the changes do not reflect on both custom-dir and other-custom-dir, is there any way ctrlB and ctrlC's scope value automatically reflect the changes made in scope under ctrlA?
Thanks very much for the help!
Thanks all for the kind help!! I finally figure out why the change cannot be reflected, I watch the object parameter to see if there are changes, but watch only monitor the object reference instead of the actual content, after deep watching the object parameter, I can finally get the watch work! Thanks for all the help
<custom-dir para="{data: data}"></custom-dir>
Then in directive's link function
scope.$watch('para.data', function(n,o){
alert('changed')
}, true); //>> The true is important!!
The fact that you need to share scope is a bit weird knowing that you have a parent controller that can contain your $scope item
Pass the value to attribute in the <custom-dir> and <other-custom-dir>
<custom-dir data="data"> </custom-dir>
Observe the change from the directive
attrs.$observe('data', function(value){
// call your directive controller here ...
})
The Benefit :
By passing data from attribute, the directive do not have to know about the controller/the source of the data, so, this reduce dependecy.
It's considered a best practice to use "controllerAs" and no longer use $scope.
By writing:
<div ng-controller='ctrlA as a'>
<button ng-click='a.updateFactoryData(data)'></button>
<!-- ... -->
</div>
and:
function ctrlA () {
this.data = [];
this.updateFactoryData = function (data) {
//...
}
}
You access your controller's data with a.data everywhere inside your div.
Basically what you require is here is share the factory data changes in your directives. So you can bind your desired factory data using different approaches based on your requirements(i.e. # attribute,= 2 way model, & expression bindings) in directives and than watch those variables in directives link functions (i.e. ideal place where you needs to handle those watch conditions) for changes so once anything will update on factory (through button click), it will automatically propagated in your directives. Here is the example to do different bindings.
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
/* NOTE: Normally I would set my attributes and bindings
to be the same name but I wanted to delineate between
parent and isolated scope. */
isolatedAttributeFoo:'#attributeFoo',
isolatedBindingFoo:'=bindingFoo',
isolatedExpressionFoo:'&'
}
};
})
<my-component attribute-foo="{{foo}}" binding-foo="foo"
isolated-expression-foo="updateFoo(newFoo)" >
<h2>Attribute</h2>
<div>
<strong>set:</strong> <input ng-model="isolatedAttributeFoo">
<i>// This does not update the parent scope.</i>
</div>
<h2>Binding</h2>
<div>
<strong>get:</strong> {{isolatedBindingFoo}}
</div>
<h2>Expression</h2>
<div>
<input ng-model="isolatedFoo">
<button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">
Submit</button>
<i>// And this calls a function on the parent scope.</i>
</div>
</my-component>
I have made sample demo to illustrate the approach please check this.

Calling controller functions from the view in AngularJS

I have a function in my BlogController which changes the height of a div.
$scope.setTopBackgroundHeight = function (screenProportion, targetDiv) {
globalService.setTopBackgroundHeight(screenProportion, targetDiv);
};
I am using this controller on a few pages, but only want to call this function on one page. So I put the call in my view as follows.
<div id="primary"
class="content-area blog-page"
ng-controller="blogCtrl">
{{$scope.setTopBackgroundHeight("half", ".background-container");}}
</div>
Now, this works. But is calling a function from within curly braces in the view ok to do style wise? I've tried to find examples of doing something like this in the angular way, but can't see anything. Should it be in some ng directive?
Yes, all DOM manipulation should be done inside directives. So In this case it'd be better if you had a directive attached to the div that called that service method.
HTML:
<div id="primary"
class="content-area blog-page"
ng-controller="blogCtrl"
setBGHeight>
</div>
JS:
app.directive('setBGHeight', function(globalService) {
return {
link: function() {
globalService.setTopBackgroundHeight("half", ".background-container");
}
}
));
This is what directives are for. Make sure to prefix them like angular does with "ng-click" but don't use ng.

create HTML element dynamically

I am very new to angular js. I want to create an input box on click of particular div. Here I need to create element on div which repeating.
<div><div ng-repeat ng-click="create();"></div><div>
What will be the best way to do so?
DOM manipulation in Angular is done via directives (There is paragraph on 'Creating a Directive that Manipulates the DOM' here)
First, read through this excellent article: How do i think in Angular if i have a jQuery background
The Angular Team also provides a pretty neat tutorial, which definetly is worth a look: http://docs.angularjs.org/tutorial
While Angular is pretty easy and fun to use once you have wrapped your head around the concepts, it can be quite overwhelming to dive into the cold. Start slow and do not try to use each and every feature from the beginning. Read a lot.
I strongly recommend egghead.io as a learning resource. The video-tutorials there are bite-sized and easy to watch and understand. A great place for both beginners and intermediates. Start from the bottom here.
Some folks have done great things with Angular. Take a look at http://builtwith.angularjs.org/ and check out some source code.
Use an array and ng-repeat to do that. Have a look at the following code.
I crated scope variable as an empty array. Then created a function to add values to that array.
app.controller('MainCtrl', function($scope) {
$scope.inputFields = [];
$scope.count = 0;
$scope.addField = function(){
$scope.inputFields.push({name:"inputText"+$scope.count++});
}
});
I used ng-repeat with this array. and called the function on the click event of a div.
<div ng-click="addField()">Click here to add</div>
<div ng-repeat="inputField in inputFields">
<input type="text" name="inputField.name">
</div>
Check this working link
Update - Show only one text box on click
I created addField() as follows.
$scope.addField = function(){
$scope.newTextField = "<input type='text' name='myTxt'>";
}
To render this html in my view file I created a new directive called compile as follows.
app.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
});
Then used this directive in my view.html file
<body ng-controller="MainCtrl">
<div ng-click="addField()">Click to Add</div>
<div compile="newTextField"></div>
</body>
click here to view the working link

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.

Categories

Resources