angularjs ng-if for defined but not valued objects - angularjs

I have a controller that has a scope object named asd and,
var app = angular.module("app",[]);
app.controller("appCtrl", function($scope){
$scope.asd = {
"name": ""
}
});
And I am using it in html code with ng-if like this.
<div ng-app="app">
<div ng-controller="appCtrl">
<p ng-if="asd.name">
Defined {{asd.name}}
</p>
<p ng-if="!asd.name">
Non Defined
</p>
</div>
</div>
This code writes Non Defined but it defined. Demo
Does ng-if looks for object value? How can I use defined property of an object?

Using angular.isDefined is a good suggestion. In that case, it is best to change your code by removing:
<p ng-if="asd.name">
Defined {{asd.name}}
</p>
<p ng-if="!asd.name">
Non Defined
</p>
And instead replacing it with a binding to a scope variable - then the checking for asd.name can be done inside your controller like this:
$scope.varStatus = "";
if(angular.isDefined($scope.asd.name)){
$scope.varStatus = "Defined" $scope.asd.name;
}
else{
$scope.varStatus = "Non Defined";
}
Then in your template, you do this (notice I only use scope variable varStatus):
<div ng-app="app">
<div ng-controller="appCtrl">
<p>
{{varStatus}}
</p>
</div>
</div>
Give it a try, I hope this helps.

Related

How to create div and assign object to dataset dynamically using Angularjs

I have below div (class name 'sp') which I would like to dynamically create based on the sk from a dataset object.
div code
<div style="" class="swindow">
<div class="sp" style="">
<div class="svis" style="">
<div style="height:95%;width:95%;margin-top:0px;margin-left:5px;">
<chart dsn="dyndata" editable="false" labelled="true"></chart>
</div>
</div>
<div class="sdata" style="">
<div class="stext" style="">Average:78% </div>
</div>
</div>
While searching for similar examples, I came across ng-repeat in Angular js and I thought it might suit for this kind of objective.
But am very new to Angular js and not sure how to assign the data to my dyndata variable dynamically and create new div (class=sp) for each of the given id.
Here is the lookup object
[
{"id":20,"st":[{"label":"Audi","value":10},{"label":"BMW","value":70}]},
{"id":26,"st":[{"label":"Benz","value":40},{"label":"BMW","value":20}]},
{"id":12,"st":[{"label":"AUDI","value":60},{"label":"Tesla","value":70}]},
{"id":57,"st":[{"label":"MZ","value":30},{"label":"Honda","value":40}]}
]
When I input the id's as a set [12,26,57] - Three divs (each for #sp) should get created one for each of ids. In those, each div should have the dyndata assigned with the respective 'st' from above javascript object.
I could create div's in jquery using .append function to the container (#swindow) each time when I need. But am not sure how to assign sk as input to dyndata dataset for each div that gets created.
Could you please share how this can be achieved using Angular js ?
Here is the angular js code I used -
<script>
var app = angular.module('ExampleApp', ['ui.plot']);
app.controller('PlotCtrl', function ($scope) {
$scope.dyndata={};
});
</script>
I'm not exactly sure what you're trying to do but I think it should look something like this. Here is a plnkr..
Controller:
app.controller('PlotCtrl', function($scope) {
$scope.items = [
{"id":20,"st":[{"label":"Audi","value":10},{"label":"BMW","value":70}]},
{"id":26,"st":[{"label":"Benz","value":40},{"label":"BMW","value":20}]},
{"id":12,"st":[{"label":"AUDI","value":60},{"label":"Tesla","value":70}]},
{"id":57,"st":[{"label":"MZ","value":30},{"label":"Honda","value":40}]}
]
});
HTML:
<body ng-controller="PlotCtrl">
<div style="" class="swindow">
<div class="sp" style="" ng-repeat="item in items">
<div class="svis" style="">
<strong>{{item.id}}:</strong>
<div>-{{item.st[0].label}}</div>
<div>-{{item.st[1].label}}</div>
<div style="height:95%;width:95%;margin-top:0px;margin-left:5px;">
<chart dsn="dyndata" editable="false" labelled="true"></chart>
</div>
</div>
<div class="sdata" style="">
<div class="stext" style="">Average:78% </div>
<br>
</div>
</div>
</div>
</body>

Why is my ng-hide / show not working with my ng-click?

I want to show the elements that contain displayCategory.name with the ng-click above it, but it's not working as expected.
.divider-row
.row-border(ng-hide="showMe")
.row.row-format
.col-xs-12.top-label
Find where you stand
%hr.profile
.row.labelRow
.col-xs-12
%ul
%li(ng-repeat='category in service.categories')
.clear.btn.Category(ng-click='thisCategory(category) ; showMe = true') {{category.name}}
.divider-row
.row-border(ng-show="showMe")
.row.row-format
.col-sm-12.col-md-12.top-label.nopadLeft
What do you think about {{displayCategory.name}}
I dropped your haml into a converter and this is what it spat out (clearly incorrect):
<div class="divider-row">
<div class="row-border">(ng-hide="showMe")
<div class="row row-format">
<div class="col-xs-12 top-label">
Find where you stand
</div>
</div>
<hr class="profile"/>
<div class="row labelRow">
<div class="col-xs-12">
<ul>
<li>(ng-repeat='category in service.categories')
<div class="clear btn Category">(ng-click='thisCategory(category) ; showMe = true') {{category.name}}</div>
</li>
</ul>
</div>
</div>
</div>
<div class="divider-row"></div>
<div class="row-border">(ng-show="showMe")
<div class="row row-format">
<div class="col-sm-12 col-md-12 top-label nopadLeft">
What do you think about {{displayCategory.name}}
</div>
</div>
</div>
</div>
So after some quick googling I found that you should be writing it like this:
.divider-row
.row-border{"ng-hide" => "showMe"}
.row.row-format
.col-xs-12.top-label
Find where you stand...
As that will convert to what you need:
<div class="divider-row">
<div class="row-border" ng-hide="showMe">
<div class="row row-format">
<div class="col-xs-12 top-label">
Find where you stand
Using curly braces instead of round ones for attributes
I cannot run your code to verify, but I think the problem is that the binding property showMe should be replaced with some object like status.showMe.
For example, define $scope.status = { showMe: false}; outside the ng-repeat (in your controller maybe).
Please check a working demonstration: http://jsfiddle.net/jx854d3y/1/
Explanations:
ng-repeat creates a child scope for each item. The child scope prototypical inherits from the parent scope. In your case, the primitive showMe is assigned to the child scope. While you use it outside the ng-repeat, where it tries to get the value from the parent scope, which is undefined. That is why it is not working.
Basic rule is: always use Object, instead of primitive types, for binding.
For more details, please refer to: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Can I "name" a filter and refer to it as a scope variable?

I'd like to do something like this. The use case is I am showing a table with a configurable set of columns, each of which may have a filter associated with it. See this fiddle.
<div ng-app="">
<div ng-controller="MyCtrl">
{{money | filterStr}}
</div>
</div>
function MyCtrl($scope) {
$scope.money = 33;
$scope.filterStr = 'currency:"USD$"';
}
So as you can see, I basically want to store the filter string text as a scope variable, and then refer to it in the html by its name. This doesn't work, but is there a way to do something like this?
If you absolutely needed to save a reference to the filter dynamically within your controller $scope, you could create a reference to the filter function within a controller variable and then call it in the HTML like you would any other function or you could run the filter on your data in your controller and save the output to a variable. Here are two examples of doing this with the currency filter (JS Fiddle here):
<div ng-app="">
<div ng-controller="MyCtrl">
{{ moneyWithFilter }}
{{ currencyFilter(money, "USD$") }}
</div>
</div>
function MyCtrl($scope, currencyFilter) {
$scope.money = 33;
$scope.moneyWithFilter = currencyFilter($scope.money, "USD$");
$scope.currencyFilter = currencyFilter;
}
Notice that you have to append the string 'Filter' to the desired filter in order to inject it into your controller. You can read more about that here. I hope this helps!
I do something like this with
<a ng-click="setCurrent(m)">
{{m.name}}
</a>
<p ng-repeat="L in List | filter:current.name">
<a ng-click="add(w)">
{{w.Name}}
</a>
</p>
Then
function setCurrent(m) {
$scope.current = m;
}

Angular ng-switch with boolean

I want to check boolean data with angular ng-switch
this is my code. but it is not working
<div ng-switch={{Item.ItemDetails.IsNew}}>
<div ng-switch-when="true">
<p class="new fontsize9 fontWeightBold">NEW</p>
</div>
</div>
<div ng-switch={{Item.ItemDetails.IsFeatured}}>
<div ng-switch-when="true">
<div class="featured">
<p class="fontWeightBold fontsize8">featured</p>
</div>
</div>
</div>
values of {{Item.ItemDetails.IsNew}} and {{Item.ItemDetails.IsFeatured}} are true or false
Convert the boolean to a string:
<div ng-switch="Item.ItemDetails.IsNew.toString()">
<div ng-switch-when="true">
If you are just checking for true values, ng-if seems more appropriate and reduces the need for additional divs containing the code, reducing your sample too:
<div ng-if="Item.ItemDetails.IsNew">
<p class="new fontsize9 fontWeightBold">NEW</p>
</div>
<div class="featured" ng-if="Item.ItemDetails.IsFeatured">
<p class="fontWeightBold fontsize8">featured</p>
</div>
Full docs at: http://docs.angularjs.org/api/ng.directive:ngIf
This syntax works for me:
<div ng-switch="Item.ItemDetails.IsFeatured">
<div ng-switch-when="true">FEATURED ITEM HTML</div>
<div ng-switch-default>REGULAR ITEM HTML (not featured)</div>
</div>
You should remove the {{}} from the ng-switch:
Change this <div ng-switch={{Item.ItemDetails.IsNew}}>
to <div ng-switch=Item.ItemDetails.IsNew>
The attribute value of ng-switch are interpreted as literal string values to match against. (Meaning that cannot be expressions.) For example, ng-switch-when="someVal" will match against the string "someVal" not against the value of the expression $scope.someVal.
If you really have to use ng-switch, it can be forced to semi-use evaluative expressions by the workaround of the .toString() javascript method. Example, using the scope variables numeric 'lastSortIndex' and the boolean 'reverseSorted', plus the AngularJS HTML variable '$index':
<div ng-switch="((lastSortIndex === $index).toString()+(reverseSorted).toString())">
<div ng-switch-when="truetrue">
<span class="glyphicon glyphicon-chevron-up">{{ header }}</span>
</div>
<div ng-switch-when="truefalse">
<span class="glyphicon glyphicon-chevron-down">{{ header }}</span>
</div>
<div ng-switch-default>{{header}}</div>
</div>
Note the above example is concatenating the booleans together and then evaluating their string contents. Would be better to move this into a callable function that returns a string to be evaluated in the switch-case.
Though I would recommend if possible for you to keep the logic in the logic-controllers area of the code (the javascript files). You can use the ng-html-safe AngularJS directive in combination with their Sanitize feature to call a function in Javascript that switches and returns desired snippets of HTML code for you. Example:
index.html:
<html ng-app="myApp">
<head>
<script src="https://code.angularjs.org/1.3.13/angular-sanitize.js">
</head>
<body ng-controller="MainController">
<!-- add your other code, like a table code here -->
<div ng-bind-html="HeaderSortIcon(lastSortIndex, $index, reverseSorted, header)">
</div>
</body>
script.js:
var myApp = angular.module('myApp ', ['ngSanitize']);
$scope.HeaderSortIcon = function (lastSortIndex, $index, reverseSorted, header) {
if (lastSortIndex === $index) {
if( reverseSorted )
{
return '<div><span class="glyphicon glyphicon-chevron-up"></span>' + header + '</div>';
}
else{
return '<div><span class="glyphicon glyphicon-chevron-down"></span>' + header + '</div>';
}
}
else {
return header;
}
}

Behavior of assignment expression invoked by ng-click within ng-repeat

I'm attempting to update my model using ng-click attached to a <p>.
I have no problem with an assignment expression outside of an ng-repeat, or with calling a scope method inside the ng-repeat. However, if I use an assignment inside the ng-repeat, it appears to be ignored. I don't see any messages reported in the Firefox console, but haven't tried setting breakpoints to see if the event is being fired.
<!DOCTYPE html>
<html>
<head>
<title>Test of ng-click</title>
<script type='text/javascript' src='http://code.angularjs.org/1.1.1/angular.js'></script>
<script type='text/javascript'>//<![CDATA[
function MyCtrl($scope) {
$scope.selected = "";
$scope.defaultValue = "test";
$scope.values = ["foo", "bar", "baz"];
$scope.doSelect = function(val) {
$scope.selected = val;
}
}
//]]>
</script>
</head>
<body ng-app>
<div ng-controller='MyCtrl'>
<p>Selected = {{selected}}</p>
<hr/>
<p ng-click='selected = defaultValue'>Click me</p>
<hr/>
<p ng-repeat='value in values' ng-click='selected = value'>{{value}}</p>
<hr/>
<p ng-repeat='value in values' ng-click='doSelect(value)'>{{value}}</p>
</div>
</body>
</html>
Fiddle is here, if you prefer (along with a couple of earlier variants).
Directive ngRepeat creates a new scope for each iteration, so you need to reference your variables in parent scope.
Use $parent.selected = value, as in:
<p ng-repeat='value in values' ng-click='$parent.selected = value'>{{value}}</p>
Note: Function call propagates due to prototypal inheritance.
If you want to learn more: The Nuances of Scope Prototypal Inheritance.
As #Stewie mentioned, $parent is one way to solve this issue. However, the recommended (by the Angular team) solution is to not define primitive properties on the $scope. Rather, the $scope should reference your model. Using references also avoids the issue (because primitive properties will not be created on the child scopes which hide/shadow the parent scope properties of the same name), and you don't have to remember when to use $parent:
HTML:
<p>Selected = {{model.selected}}</p>
<hr/>
<p ng-click='model.selected = defaultValue'>Click me</p>
<hr/>
<p ng-repeat='value in values' ng-click='model.selected = value'>{{value}}</p>
<hr/>
<p ng-repeat='value in values' ng-click='doSelect(value)'>{{value}}</p>
JavaScript:
$scope.model = { selected: ""};
...
$scope.doSelect = function (val) {
$scope.model.selected = val;
}
Fiddle.
I recently updated the wiki page that #Stewie mentioned to always recommend this approach.

Resources