Knockout js - visible binding with negation does not work - javascript

I am trying to use the visible data binding with a negation and it does not seem to work.
I found several questions in stackoverflow which specify that the NOT binding should be used as an expression. But in my case i am just using the length property, so i am not sure how to use an expression. Here is my example
<div class="form-group" data-bind="visible:!users.length == 0">
<span>Some message here...</span
</div>
<div class="form-group" data-bind="visible:users.length > 0">
<span>User data grid here...</span
</div>

I'm guessing users is an observableArray and therefore you should be doing this:
data-bind="visible:users().length !== 0"
An even better and more clear intent would be to create a computed property on your view model and bind to that instead:
showUsers = ko.computed(function(){
return _this.users().length > 0;
});
Then your bindings become:
data-bind="visible:showUsers"
Or
data-bind="visible:!showUsers()"
Here is a jsFiddle showing a full example using various techniques.

Related

Angular show hide with combine condition

I have an array of object need to show hide based on filter like below:
HTML CODE:
Filter:
<div (click)="filter(1)"> F1 </div>
<div (click)="filter(2)"> F2 </div>
<div (click)="filter(3)"> F3 </div>
<div (click)="filter(4)"> F4 </div>
<div *ngFor="let data of datas">
<span *ngIf="data.show">
{{data.name}}
</span>
</div>
ts Code:
this.datas = `[{'name':'product one','filter':'1'},{'name':'product two','filter':'2'},{'name':'product three','filter':'3'},{'name':'product three','filter':'3'},{'name':'product','filter':''},{'name':'product','filter':''},{'name':'product one','filter':'1'},{'name':'product'}]`
filter(query){
this.datas.forEach(function (element, index) {
if (element.filter == query ) {
element.show = true;
} else {
element.show = false;
}
I have tried the above approach it's not working .
Expected like:
By default display all product.
Filter is toggle(on/off)
Need to filter like (F1 & F2 & F3) at the same time like combination
The array objects do not have the show property that you test in the *ngIf directive
Rather simple, really.
I made you a small stackblitz app. But you also really, really need to work on your code. Even as a description for your help, this is just pretty messy.
I didn't code your "Multiple Selections" for you.
https://stackblitz.com/edit/angular-ivy-fbpgdv?file=src/app/app.component.ts
Observation/Suggestions :
Instead of adding a new property show. You can easily achieve that by filtering out the datas array based on the value passed in the filter() method.
Instead of modifying the original array, you can make a deep copy and do the operation on click on filter().
Working Demo : https://jsfiddle.net/srvpw2bo/

Compare angular index variable in smarty tags

I want to catch the first iteration in ng-repeat directive:
<div ng-repeat="product in products">
<div is-open="{if "[[$index]]" == 0}true{else}false{/if}">
...
</div>
</div>
But it doesn't work. Setting 0 as string also doesn't work. Comparing in angular also doesn't work.
How can I do that?
Try:
<div is-open="{{$index == 0}}"></div>
You should use special property $first of ng-repeat with ternary operator. Like see below snippet
<div ng-repeat="product in products">
<div is-open="($first) ? true : false">
...
</div>
</div>
I suppose smarty code will not work as you're expecting. Smarty is a server side programming language and angular runs on client side. In your query, smarty tags are unnecessary being called in angular directive. Above trick will work for you.
There are also some couple of special properties available too. You can check them out here

$scope variables shortcuts in AngularJs Templates

In my controller I assign:
$scope.currentThing.data
And in my template sometimes I need
currentThing.data.response[0].hello
and sometimes
currentThing.data.otherStuff[0].goodbye
//or
currentThing.data.anotherThing[0].goodMorning
So I was wondering if it is possible to create a shortcut for this variables straight in the templates, something like:
{{response = currentThing.data.response[0]}}
So that I can use it like this {{response.hello}}.
In general, is it possible to assign temporary variables from the template? I don't need to have any data-binding, I would need them only for generating the template and then they can disappear forever
You can do that in controller like here: http://jsbin.com/moyuhe/1/edit
app.controller('firstCtrl', function($scope){
$scope.currentThing = {
data: [
{response:[
{hello:1},
{hello:2}
]}
]
};
$scope.temp = $scope.currentThing.data[0];
});
HTML:
<div ng-controller="firstCtrl">
{{temp.response |json }}
</div>
You might be able to use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit
Although it seems that using it outside of ngRepeat is frowned upon.
<div ng-init="myvar = currentThing.data.response[0]">
<span>{{myvar.hello}}</span>
</div>
I haven't tested it like this but that's the closest thing I can think of that may solve your problem.
Yes, it is possible using syntax like
{{ variable = ( expression ) }}
anywhere in HTML template (not just ng-init as some suggest).
It is exceptionally useful in cases when you need to use a calculated variable more times - it does not need to be calculated each time.
Some example
<!-- can use it before -->
<p> Calculated value is {{calculated}} </p>
<div ng-repeat=" item in calculated = ( allItems | filter1 | filter2 | filter3 ) ">
{{item}}
</div>
<!-- can use it after-->
<p> Calculated value is still {{calculated}} </p>
Edit: so in your case
{{response = ( currentThing.data.response[0] ) }}

Should AngularJS logic be placed in HTML file?

I want to refactor code of which I post examples below. I am very new to AngularJS. Now when I saw the code, I was very curious about all the logic that is placed in the HTML code.
<p ng-show="countForm.count.$dirty && countForm.count.$error.min" class="error-message">
<button ng-click="step(2)" ng-show="data.step == 1 && countForm.count.$dirty" ng-disabled="countForm.$invalid" class="line-break">
<div ng-class="{selected: data.spreadChoice == 3}" ng-click="data.spreadChoice = 3; step(3)" ng-mouseover="data.preSpreadChoice = 3" ng-mouseout="data.preSpreadChoice = data.spreadChoice">
<div ng-show="data.step >= 2" class="step" ng-class="{active: data.step == 3, done: data.step > 3, left: data.preSpreadChoice == 1, right: data.preSpreadChoice == 3}" ng-scroll-here="data.step == 3">
<p ng-switch-when="false" class="large">[[data.emails.length]] von [[data.count]] – <span class="red">[[Math.max(0,data.count-data.emails.length)]]</span> Members</p>
<div ng-show="data.step >= 5 && data.multipleTeams" class="step" ng-class="{done: data.step > 5, active: data.step == 5}" ng-scroll-here="data.step == 5">
<button class="small" ng-disabled="!unitsForm.$dirty || unitsForm.$invalid" ng-click="addUnit(data.nextTeam, data.nextTeamleaderEmail)">
Shouldn't the HTML rather contain classes or attributes and the logic itself should be placed in JS files or JS code? Is this a good (or at least a common) way of developing AngularJS? Or should placing logic in HTML be avoided?
If you ask me:
Client side business logic sits in services that are injected into directives\controllers.
UI logic is suppose to be placed in the controllers.
Now about adding logic to the views, if we are talking about business logic then it's a big no no. Use a method on your controller that will evaluate stuff using the service.
If we are talking about ng-if/ng-show conditions then only if they are small and "readable" conditions I would add them to the view. When it's more than that, I move them to the controller for debugging issues and since I believe the HTML should be readable.
Placing logic in HTML using directives in angular is a good way. You cannot take full advantage of angular without placing logic in HTML.
Controllers should contain view logic, but shouldn’t actually reference the DOM (referencing the DOM should only be done through directives). ref
Two things to remember or the best practices for AngularJS are
Treat the scope as read-only in views
Treat the scope as write-only in controllers
ref
Since you are placing logic in HTML, if you treat it as read-only, you can check conditions or extract data using functions in scope, but the original data model isn't disturbed whatever you do in HTML.
Also tying dom elements to specific directives are the most powerful features of angular.
When you use a datepicker, in jQuery, you could do as follows:
<div id="datepicker"></div>
then in JS:
jQuery('#datepicker').datepicker({
start:'today',
end:'tomorrow',
showTime:true
})
You can do this in angular way as follows
This way even when a designer or someone who reads HTML will be able to read what and even you can pass the options from the element's attributes itself.
<div date-picker start="today" end="tomorrow" show-time="true"></div>
AngularJS's importance itself is declarative syntax and can contain expressions as attribute values like you posted. That is not at all a bad practice. Indeed it is common and good practice all developers do. Using logic in HTML in angularjs saves a lot of code writing by ourselves. All the heavylifting is done by angular behind the scenes.
See some best practices about AngularJS

define a variable inside a jsrender template

I need to keep a "colcounter" variable inside the loop that will be used to fill a jsrender template.
Here is my template code
<script id="datascapeTemplate" type="text/x-jsrender">
<div id="dsViewport">
<div class="ds-column" style="width:{{:(name.length*100)}}px;">
<h1 id="datascapeName">{{:name}}</h1>
<div><span id="dsToggle">toggle</span></div>
</div>
{{=colcounter}}
{{for sections}}
<div class="ds-section">
<h3>{{:label}}</h3>
<div class="ds-column" id="start">
{{for items}}
{{* if (colcounter > 4){
colcounter = 1;
}}
</div>
<div class="ds-column" id="start">
{{* } }}
{{*
if ( data.selected || datascape.showInvisible) { }}
<div class="ds-item {{* if (data.featured){ }} nowActive {{*} }} {{* if (data.active){ }} nowActiveRed {{*} }}" background="{{:background}}" bgcolor="#000000" fgcolor="#FFFFFF">
<div class="ds-item-container">
<h4>{{:title}}<br/>{{:time}}</h4>
<p><a item="{{:id}}" href="{{:url}}" class="itemLink">view file {{:colcounter}}</a></p>
</div>
</div>
{{* colcounter++; }}
{{* } }}
{{/for}}
</div>
{{* colcounter=1; }}
</div>
{{/for}}
{{* colcounter=1; }}
</div>
</script>
Unfortunately, it prints, on the very first iteration of the loop "Error: colcounter is not defined.". Afterwards it works.
It seems the way i initialise my colcounter variable is not working but i fail to find the correct way. var colcounter =0 does not work.
UPDATE
jsfiddle: http://jsfiddle.net/ZX6Mk/
colcounter works now. I declared it in the global scope. But I have an issue with datascape.showInvisible. It also triggers the error
Error: Cannot read property 'showInvisible' of undefined.
Thank you for your time,
a.
I took your fiddle and made a few changes. http://jsfiddle.net/johnpapa/bLSkz/
The toggleButton was being referred to in jQuery without the #. So I added that.List item, otherwise the click was not being captured.
Your fiddle did not reference jQuery nor JsRender, though you were using both, so I added them. (I assume you never ran the fiddle)
There was no datascape.showInvisible property, so I created one.
I passed showInvisible to the inner for loop using a parameter, so it could be accessed in its context.
{{for sections ~showIt=showInvisible}}
{{if (editorspick_amount > 0 || ~showIt)}}
The template you were trying to render did not exist, so I changed the rendering code to use the script tag you created. This also sets the allowCode=true, which is required to safely turn on the allowCode feature.
$.templates("myTmpl", {markup: "#datascapeTemplate", allowCode: true });
$('#toggleButton').click(function(){
if(!rendered){
rendered = true;
$("#datascape").html(
$.render.myTmpl( datascape.json )
).show();
}
});
I changed one place where you used {{* }} to instead use an {{if}} block since there was no need to use allow code.
This allowed all of the code to run and the template to render, though I admittedly did not follow all of what you were trying to do.
Hope this helps.
One suggestion ... the allowCode feature makes for really ugly templates and hard to maintain and read. I highly recommend replacing it with helper functions (or other constructs). For example, you used allowCode to create the styling for some elements. You could have used a custom tag for this instead, and moved the logic to javascript and simplified your template. The colcounter could be moved to a helper function. It's just much more readable to move the logic to javascript, and keep the template/html clean. Just my 2 cents :)

Categories

Resources