Angular Js Show the Checkbox's Checked when Page Loads - javascript

Angular Js Show the Checkbox's Checked when Page Loads.
I am saving the Checkboxes. when I Reload the Page I want to show the selected checkboxes
<md-checkbox ng-repeat="primaryPrograms in ctrl.primaryProgramStudies" ng-model="ctrl.primaryProgramStudiesSelected[primaryPrograms.id]" ng-checked="primaryPrograms.selected==true">
{{primaryPrograms.name}}
</md-checkbox>
Script :
ctrl.primaryProgramStudiesSelected =
[{"id":1,"name":"SAT","selected":false},{"id":2,"name":"ACT","selected":true},{"id":3,"name":"PSAT","selected":false},{"id":4,"name":"ISEE\/SSAT","selected":false},{"id":5,"name":"AP","selected":true},{"id":6,"name":"General GPA Management","selected":true},{"id":7,"name":"Reading","selected":false},{"id":8,"name":"Math","selected":false},{"id":9,"name":"Science","selected":false},{"id":10,"name":"Social Studies","selected":false},{"id":11,"name":"ESL","selected":true},{"id":12,"name":"College Admissions","selected":true},{"id":13,"name":"TOEFL ","selected":false}]]`

ngChecked directive should not be used together with ngModel, as this can lead to unexpected behavior.
https://docs.angularjs.org/api/ng/directive/ngChecked
angular.module('MyApp',['ngMaterial', 'ngMessages'])
.controller('AppCtrl', function($scope) {
$scope.items = [{"id":1,"name":"SAT","selected":false},{"id":2,"name":"ACT","selected":true},{"id":3,"name":"PSAT","selected":false},{"id":4,"name":"ISEE\/SSAT","selected":false},{"id":5,"name":"AP","selected":true},{"id":6,"name":"General GPA Management","selected":true},{"id":7,"name":"Reading","selected":false},{"id":8,"name":"Math","selected":false},{"id":9,"name":"Science","selected":false},{"id":10,"name":"Social Studies","selected":false},{"id":11,"name":"ESL","selected":true},{"id":12,"name":"College Admissions","selected":true},{"id":13,"name":"TOEFL ","selected":false}];
});
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-sanitize.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-messages.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="AppCtrl" class="md-padding demo checkboxdemoSelectAll">
<div layout="row" layout-wrap="">
<div flex="100" layout="column">
<div>
<fieldset class="demo-fieldset">
<legend class="demo-legend">Select </legend>
<div layout="row" layout-wrap="" flex="">
<div class="demo-select-all-checkboxes" flex="100">
<md-checkbox ng-repeat="item in items" ng-model="item.selected">
{{ item }}
</md-checkbox>
</div>
</div>
</fieldset>
</div>
</div>
</div></div>
</div>
While reload the app, Everything reload & the code is render freshly. And whatever changes made in client side(without server side), everything gone.
So as per #Pengyy comment you have to store the selected items to server / cookies / localstorage. Then when reload pages just read the stored data and reset check boxes.

Change ng-model="ctrl.primaryProgramStudiesSelected[primaryPrograms.id]" to ng-model="ctrl.primaryProgramStudiesSelected[primaryPrograms.selected]".
Then add selected property to every object in your primaryProgramStudiesSelected array. If you want it to be selected by default, make the selected property true.

Can you try something like this:
<div ng-repeat="primaryPrograms in ctrl.primaryProgramStudies">
<div class="checkbox">
<label>
<input ng-model="primaryPrograms.selected" ng-true-value="true" ng-false-value="false" type="checkbox" ng-checked="primaryPrograms.selected === true"> Checked
</label>
</div>
</div>
Note: if you are using mysql your true/false fields are probably tiny int, and you should use ng-true-value="1" ng-false-value="0".
Also note that in controller you already should set selected to true, im not sure how you get your data and how you know if field is selected. But this example should work.

Related

ng-message does not seem to work

I have a piece of code on which angularjs ng-message doesnot seem to work.
Here is a JSfiddle
<div ng-app="app" ng-controller="myctrl">
<form name="myform" novalidate>
error: {{myform.definition.$error}}
<textarea ng-blur="handleBlur(myform)"
name="definition"
ng-model="$ctrl.definition"
ng-blur="$ctrl.handleBlur(myform)">
</textarea>
<div ng-messages="myform.definition.$error">
<div ng-message="validationError">
Please enter a value for this field.
</div>
</div>
</form>
</div>
controller:
angular.module('app', []).controller('myctrl', function($scope) {
$scope.someval = true;
$scope.handleBlur = function(form) {
form.definition.$error.validationError = false;
$scope.someval = !$scope.someval
form.definition.$error['validationError'] = $scope.someval;
}
})
From the docs, https://docs.angularjs.org/api/ngMessages#dynamic-messaging
Feel free to use other structural directives such as ng-if and
ng-switch to further control what messages are active and when. Be
careful, if you place ng-message on the same element as these
structural directives, AngularJS may not be able to determine if a
message is active or not. Therefore it is best to place the ng-message
on a child element of the structural directive.
From:
<div ng-messages="myform.definition.$error">
<div ng-message="validationError">
Please enter a value for this field.
</div>
</div>
To:
<div ng-messages="myform.definition.$error">
<div ng-if="showRequiredError">
<div ng-message="validationError">
Please enter a value for this field.
</div>
</div>
</div>

AngularJS advice on how to fix a bug when pushing two of the same strings into the array

I'm having trouble trying to figure out how to fix a bug that happens when I try to push the same string as added previously to the array. It gets stuck and will not allow the app to post another string.
How do I make sure that your repeat doesn't get stuck when there two of the same values in the array?
Bug Example Screenshot
--> Bug happens when I try to push "1"into the array again after a "1" is already posted.
HTML Code
<body>
<div data-ng-controller="appController" class="container">
<div class="row">
<form>
<label for = "status"> Status: </label>
<input data-ng-model = "input_data" type="text" id="status"/>
<button data-ng-click="add_data()"> OK </button>
<ul class = "list-group">
<li class="list-group-item" data-ng-repeat="x in array_data">
{{x}}
<button data-ng-click = "remove_data($index)">DEL</button>
</li>
</ul>
</form>
</div>
</div>
<script src="framework/js/jquery.min.js"></script>
<!-- All Bootstrap plug-ins file -->
<script src="framework/js/bootstrap.min.js"></script>
<!-- Basic AngularJS -->
<script src="framework/js/angular.min.js"></script>
<!-- Your Controller -->
<script src="framework/js/appstatpost.js"></script>
</body>
AngularJS code
var app = angular.module("myApp", []);
app.controller("appController", function ($scope) {
$scope.array_data = [];
$scope.add_data = function () {
$scope.array_data.push($scope.input_data);
};
$scope.remove_data = function (index) {
$scope.array_data.splice(index, 1);
};
});
You could use track by $index, example:
<li class="list-group-item" data-ng-repeat="x in array_data track by $index">
AngularJS tries by default to find a key in your array to index by. Normally this works well, but if you have duplicates then you have to tell AngularJS to make a new index, in this case, $index.

Using ng-if to check angular variable from another directive in angularjs

I am new to angular. I have a task to display json data in specific design, but I have not idea about nesting of json. Is it possible to check if the data is json or an array of json and then display the output.
Here I am trying to display data only if it is an array. But it is not working. Kindly help.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="readJson as rj">
<div ng-repeat="d in rj.data">
<ul>
<div ng-model="myVar" ng-init="myVar = "{{isArray(d.third)}}>
<div ng-if="myVar">
<li>{{d.third}}</li>
</div>
</ul>
</div>
</div>
</div>
</body>
<script>
(function(){
var app=angular.module('myApp',[]);
app.controller('readJson',function($scope){
$scope.isArray = angular.isArray;
this.data=[{"first":"one","second":"two","third":"three"},
{"first":"ONE","second":"two","third":"three"},
{"first":"onE","second":"two","third":
[
{"first":"1one","second":"2two","third":"3three"},
{"first":"1ONE","second":"2two","third":"3three"}
]}];
});
})();
</script>
</html>
Here you go. This example will display data only when "third" param is an array.
https://plnkr.co/edit/EX0BvcYrLPFbiN2ezlqQ
<div ng-repeat="d in data">
<ul>
<div ng-init="myVar = isArray(d.third)"></div>
<div ng-if="myVar">
<li>{{d.third}}</li>
</div>
</ul>
</div>
The problem was in ng-init="myVar = "{{isArray(d.third)}} - you need to make sure isArray(d.third) is in expression (between "") and there is no need to use {{}} syntax within ng-init directive. It will evaluate expression for you (check an example).

angularjs 1 ngModel two $watchs

I'm using angular google places directive plugin. when user selects the address then it shows on $scope.watch, but I want to watch every key hit, so I can clear other values, if user start changing any value on the input box.
Is there a way to watch for any key or value changes?
It seems like the issue in your case is that the Google Places directive does not update the variable assigned to ng-model ($scope.place) until a selection is made from the dropdown menu. This makes sense - the point is for the user to decide which place is the one they are looking for, out of several results.
Check out the source to see where this happens:
https://github.com/kuhnza/angular-google-places-autocomplete/blob/0.2.7/src/autocomplete.js#L70
https://github.com/kuhnza/angular-google-places-autocomplete/blob/0.2.7/src/autocomplete.js#L166
I'm including a code snippet of the plugin in case it will help anyone else with future debugging. You'll need to add your Maps API key to make it work.
"use strict";
angular.module('example', ['google.places'])
// Setup a basic controller with a scope variable 'place'
.controller('MainCtrl', function ($scope) {
$scope.place = null;
$scope.updatePlace = function() {
console.log($scope.place);
};
});
angular.module("google.places",[]).factory("googlePlacesApi",["$window",function(a){if(!a.google)throw"Global `google` var missing. Did you forget to include the places API script?";return a.google}]).directive("gPlacesAutocomplete",["$parse","$compile","$timeout","$document","googlePlacesApi",function(a,b,c,d,e){return{restrict:"A",require:"^ngModel",scope:{model:"=ngModel",options:"=?",forceSelection:"=?",customPlaces:"=?"},controller:["$scope",function(a){}],link:function(a,f,g,h){function i(){f.bind("keydown",l),f.bind("blur",m),f.bind("submit",m),a.$watch("selected",n)}function j(){var c,e=angular.element("<div g-places-autocomplete-drawer></div>"),f=angular.element(d[0].body);e.attr({input:"input",query:"query",predictions:"predictions",active:"active",selected:"selected"}),c=b(e)(a),f.append(c)}function k(){h.$parsers.push(o),h.$formatters.push(p),h.$render=q}function l(b){0!==a.predictions.length&&-1!==w(A,b.which)&&(b.preventDefault(),b.which===z.down?(a.active=(a.active+1)%a.predictions.length,a.$digest()):b.which===z.up?(a.active=(a.active?a.active:a.predictions.length)-1,a.$digest()):13===b.which||9===b.which?(a.forceSelection&&(a.active=-1===a.active?0:a.active),a.$apply(function(){a.selected=a.active,-1===a.selected&&r()})):27===b.which&&a.$apply(function(){b.stopPropagation(),r()}))}function m(b){0!==a.predictions.length&&(a.forceSelection&&(a.selected=-1===a.selected?0:a.selected),a.$digest(),a.$apply(function(){-1===a.selected&&r()}))}function n(){var b;b=a.predictions[a.selected],b&&(b.is_custom?a.$apply(function(){a.model=b.place,a.$emit("g-places-autocomplete:select",b.place),c(function(){h.$viewChangeListeners.forEach(function(a){a()})})}):C.getDetails({placeId:b.place_id},function(b,d){d==e.maps.places.PlacesServiceStatus.OK&&a.$apply(function(){a.model=b,a.$emit("g-places-autocomplete:select",b),c(function(){h.$viewChangeListeners.forEach(function(a){a()})})})}),r())}function o(b){var c;return b&&u(b)?(a.query=b,c=angular.extend({input:b},a.options),B.getPlacePredictions(c,function(b,c){a.$apply(function(){var d;r(),a.customPlaces&&(d=s(a.query),a.predictions.push.apply(a.predictions,d)),c==e.maps.places.PlacesServiceStatus.OK&&a.predictions.push.apply(a.predictions,b),a.predictions.length>5&&(a.predictions.length=5)})}),a.forceSelection?h.$modelValue:b):b}function p(a){var b="";return u(a)?b=a:v(a)&&(b=a.formatted_address),b}function q(){return f.val(h.$viewValue)}function r(){a.active=-1,a.selected=-1,a.predictions=[]}function s(b){var c,d,e,f=[];for(e=0;e<a.customPlaces.length;e++)c=a.customPlaces[e],d=t(b,c),d.matched_substrings.length>0&&f.push({is_custom:!0,custom_prediction_label:c.custom_prediction_label||"(Custom Non-Google Result)",description:c.formatted_address,place:c,matched_substrings:d.matched_substrings,terms:d.terms});return f}function t(a,b){var c,d,e,f=a+"",g=[],h=[];for(d=b.formatted_address.split(","),e=0;e<d.length;e++)c=d[e].trim(),f.length>0&&(c.length>=f.length?(x(c,f)&&h.push({length:f.length,offset:e}),f=""):x(f,c)?(h.push({length:c.length,offset:e}),f=f.replace(c,"").trim()):f=""),g.push({value:c,offset:b.formatted_address.indexOf(c)});return{matched_substrings:h,terms:g}}function u(a){return"[object String]"==Object.prototype.toString.call(a)}function v(a){return"[object Object]"==Object.prototype.toString.call(a)}function w(a,b){var c,d;if(null==a)return-1;for(d=a.length,c=0;d>c;c++)if(a[c]===b)return c;return-1}function x(a,b){return 0===y(a).lastIndexOf(y(b),0)}function y(a){return null==a?"":a.toLowerCase()}var z={tab:9,enter:13,esc:27,up:38,down:40},A=[z.tab,z.enter,z.esc,z.up,z.down],B=new e.maps.places.AutocompleteService,C=new e.maps.places.PlacesService(f[0]);!function(){a.query="",a.predictions=[],a.input=f,a.options=a.options||{},j(),i(),k()}()}}}]).directive("gPlacesAutocompleteDrawer",["$window","$document",function(a,b){var c=['<div class="pac-container" ng-if="isOpen()" ng-style="{top: position.top+\'px\', left: position.left+\'px\', width: position.width+\'px\'}" style="display: block;" role="listbox" aria-hidden="{{!isOpen()}}">',' <div class="pac-item" g-places-autocomplete-prediction index="$index" prediction="prediction" query="query"',' ng-repeat="prediction in predictions track by $index" ng-class="{\'pac-item-selected\': isActive($index) }"',' ng-mouseenter="selectActive($index)" ng-click="selectPrediction($index)" role="option" id="{{prediction.id}}">'," </div>","</div>"];return{restrict:"A",scope:{input:"=",query:"=",predictions:"=",active:"=",selected:"="},template:c.join(""),link:function(c,d){function e(c){var d=c[0],e=d.getBoundingClientRect(),f=b[0].documentElement,g=b[0].body,h=a.pageYOffset||f.scrollTop||g.scrollTop,i=a.pageXOffset||f.scrollLeft||g.scrollLeft;return{width:e.width,height:e.height,top:e.top+e.height+h,left:e.left+i}}d.bind("mousedown",function(a){a.preventDefault()}),a.onresize=function(){c.$apply(function(){c.position=e(c.input)})},c.isOpen=function(){return c.predictions.length>0},c.isActive=function(a){return c.active===a},c.selectActive=function(a){c.active=a},c.selectPrediction=function(a){c.selected=a},c.$watch("predictions",function(){c.position=e(c.input)},!0)}}}]).directive("gPlacesAutocompletePrediction",[function(){var a=['<span class="pac-icon pac-icon-marker"></span>','<span class="pac-item-query" ng-bind-html="prediction | highlightMatched"></span>','<span ng-repeat="term in prediction.terms | unmatchedTermsOnly:prediction">{{term.value | trailingComma:!$last}} </span>','<span class="custom-prediction-label" ng-if="prediction.is_custom"> {{prediction.custom_prediction_label}}</span>'];return{restrict:"A",scope:{index:"=",prediction:"=",query:"="},template:a.join("")}}]).filter("highlightMatched",["$sce",function(a){return function(b){var c,d="",e="";return b.matched_substrings.length>0&&b.terms.length>0&&(c=b.matched_substrings[0],d=b.terms[0].value.substr(c.offset,c.length),e=b.terms[0].value.substr(c.offset+c.length)),a.trustAsHtml('<span class="pac-matched">'+d+"</span>"+e)}}]).filter("unmatchedTermsOnly",[function(){return function(a,b){var c,d,e=[];for(c=0;c<a.length;c++)d=a[c],b.matched_substrings.length>0&&d.offset>b.matched_substrings[0].length&&e.push(d);return e}}]).filter("trailingComma",[function(){return function(a,b){return b?a+",":a}}]);
.pac-container{background-color:#fff;position:absolute!important;z-index:1000;border-radius:2px;border-top:1px solid #d9d9d9;font-family:Arial,sans-serif;box-shadow:0 2px 6px rgba(0,0,0,.3);-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden}.pac-container:after{content:"";padding:1px 1px 1px 0;height:16px;text-align:right;display:block;background-image:url(//maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white2.png);background-position:right;background-repeat:no-repeat;background-size:104px 16px}.hdpi.pac-container:after{background-image:url(//maps.gstatic.com/mapfiles/api-3/images/powered-by-google-on-white2_hdpi.png)}.pac-item{cursor:default;padding:0 4px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;line-height:30px;text-align:left;border-top:1px solid #e6e6e6;font-size:11px;color:#999}.pac-item:hover{background-color:#fafafa}.pac-item-selected,.pac-item-selected:hover{background-color:#ebf2fe}.pac-matched{font-weight:700}.pac-item-query{font-size:13px;padding-right:3px;color:#000}.pac-icon{width:15px;height:20px;margin-right:7px;margin-top:6px;display:inline-block;vertical-align:top;background-image:url(//maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons.png);background-size:34px}.hdpi .pac-icon{background-image:url(//maps.gstatic.com/mapfiles/api-3/images/autocomplete-icons_hdpi.png)}.pac-icon-search{background-position:-1px -1px}.pac-item-selected .pac-icon-search{background-position:-18px -1px}.pac-icon-marker{background-position:-1px -161px}.pac-item-selected .pac-icon-marker{background-position:-18px -161px}.pac-placeholder{color:gray}.custom-prediction-label{font-style:italic}
<head>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<!-- Required dependencies -->
<script src="https://maps.googleapis.com/maps/api/js?key=INSERT_YOUR_GMAPS_API_HERE&libraries=places"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="example" ng-controller="MainCtrl">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Basic Usage</h1>
<h5>Result:</h5>
<pre>{{place | json}}</pre>
<form class="form">
<input class="form-control" g-places-autocomplete ng-model="place" ng-change="updatePlace()"/>
</form>
</div>
</div>
</div>

Ng-repeat functionality doesnt work

Today is my first day with Angular.js , and I stuck at a basic controller :
my APP.js
(function()
{ var app = angular.module('store', [ ] );
app.controller('StoreController', function()
{
this.product = gem;
});
var gem = [
{name:'John', price:25, description:'boy',soldout: false,canpurchase:true},
{name:'Kohn', price:25, description:'boy',soldout: false,canpurchase:true}
]
//not mentioned:false
})();
Index.HTML
<!DOCTYPE html>
<html ng-app="store">
<script src="js/angular.min.js" type="text/javascript"></script>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<title>Purple</title>
</head>
<body ng-controller = "StoreController as store">
<script src="js/app.js" type="text/javascript"></script>
<h1>{{"Create your CV"}}</h1>
<div ng-repeat="products in store.product">
<div ng-hide="store.product.soldout">
<h1> {{store.product.name}} </h1>
<h2><em class="pull-right">{{store.product.price | currency}}</em></h2>
<h3> {{store.product.description}} </h3>
<button ng-show = "store.product.canpurchase"> Add to cart </button>
</div>
</div></body></html>
My code is working fine , but NG - repeat is not working, if I don't choose ng-repeat and display each item as an array then I am getting a display but not with "ng-repeat" .. Any idea's what am I missing ?
Please dont mark this as negative, I have done a lot of research before asking this question
Code on fiddle : http://jsfiddle.net/68Dkz/2/
Here is working version using controller alias store as shown. Note that product was changed to products in controller since the array contains more than one product. I think you are gtting confused about which is array and which is the individual item within the ng-repeat due to this
<div ng-repeat="product in store.products">
<div ng-hide="product.soldout">
<h1> {{product.name}} </h1>
<h2><em class="pull-right">{{store.product.price | currency}}</em></h2>
<h3> {{product.description}} </h3>
<button ng-show="product.canpurchase">Add to cart</button>
</div>
</div>
DEMO
store is your module not your scope you don't need it in the iteration, do products in product instead
<div ng-repeat="products in product">
<div ng-hide="products.soldout">
<h1> {{products.name}} </h1>
<h2><em class="pull-right">{{products.price | currency}}</em></h2>
<h3> {{products.description}} </h3>
<button ng-show = "products.canpurchase"> Add to cart </button>
</div>
</div>
stop aliasing your controller, it is unnecessary and may cause issues with the html compiler
using products as your iterator is confusing, I would suggest making the collection products and the iterator product

Categories