how to solve $injector error in angularjs? - javascript

I am new to angularjs.i try to create simple page by using some tutorial.One page is for user input html and another one javascript for if else statement.I keep receive error in console as "[$injector:unpr]". index.html
<body ng-app="ngCribs" ng-controller="cribsController">
<div class="container">
<div class="row price-form-row" ng-if="!addListing">
<span class="input-group-addon">Min Price</span>
<select name="minPrice" id="minPrice" [ng-model]="priceInfo.min" class="form-control">
<option value="100000">$100,000</option>
<option value="200000">$200,000</option>
<option value="300000">$300,000</option>
</select>
</div>
<span class="input-group-addon">Max Price</span>
<select name="maxPrice" id="maxPrice" ng-model="priceInfo.max" class="form-control">
<option value="100000">$100,000</option>
<option value="200000">$200,000</option>
<option value="300000">$300,000</option>
</select>
<div class="container">
<div class="col-sm-4"
ng-repeat="crib in cribs | cribsFilter:priceInfo | orderBy: '-id'">
<i class="glyphicon glyphicon-tag"></i> {{crib.price | currency}} <i class="glyphicon glyphicon-home"></i> {{crib.address}}
<span class="label label-primary label-sm">{{crib.type}}</span></div>
</body>
<script src="app.js"></script>
<script src="scripts/cribsFilter.js"></script>
</html>
cribsFiler.js
angular
.module('ngCribs')
.filter('cribsFilter', function() {
return function(listings, priceInfo) {
var filtered = [];
var min = priceInfo.min;
var max = priceInfo.max;
angular.forEach(listings, function(listing) {
if(listing.price >= min && listing.price <= max) {
filtered.push(listing);
}
});
return filtered;
}
});
CribsController.js
angular
.module('ngCribs')
.controller('cribsController',function($scope, cribsFactory){
$scope.priceInfo ={
min:0,
max:1000000
}
$scope.cribs;
cribsFactory.getCribs().then(function(data){
$scope.cribs = data.data;
});
(function(error){
console.log(error);
});
});
App.js
angular.module('ngCribs',['ui.bootstrap']);

Without seeing your app.js I can't be certain, but given everything else I can make the following guess: you should probably add a script tag to reference CribsController.js :-)

Related

How can I dynamically update materialize <select>?

I have a select tag with several options. I am using materizlizecss select, and I would like to use javascript to disable certain options based on certain conditions. I have read another post on how to do this, but I need to do it without jquery. When I try it, nothing happens. No errors or warnings in the console either.
<form id="code-form">
<h4 style="color: black;">Generate Code</h4>
<div class="input-field">
<select name="security-select" id="security-select">
<option style="display: none;" id="webmaster-value" value="1">Webmaster</option>
<option id="scoutmaster-value" value="2">Scoutmaster</option>
<option id="general-admin-value" value="3">General Admin</option>
<option id="spl-value" value="4">Senior Patrol Leader</option>
<option selected id="standard-user-value" value="5">Standard User</option>
</select>
</div>
<button class="btn deep-purple" id="add-code">Generate Code</button>
</form>
.
if (security == '2') {
document.querySelector('#webmaster-value').setAttribute('disabled', 'disabled')
}
You have to Re-Initialize a select field after edited it
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
document.getElementById("change-code").addEventListener("click", function () {
document.querySelector('#webmaster-value').setAttribute('disabled', 'disabled');
// Re-Initialize select
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<form id="code-form">
<h4 style="color: black;">Generate Code</h4>
<div class="input-field">
<select name="security-select" id="security-select">
<option style="display: none;" id="webmaster-value" value="1">Webmaster</option>
<option id="scoutmaster-value" value="2">Scoutmaster</option>
<option id="general-admin-value" value="3">General Admin</option>
<option id="spl-value" value="4">Senior Patrol Leader</option>
<option selected id="standard-user-value" value="5">Standard User</option>
</select>
</div>
<button type="button" class="btn deep-purple" id="change-code">Press to disable</button>
</form>

How to get the div id's of this form?

Working on an app that exports what the user typed on the app to a particular website with the similar components. For example, if the user typed a title on the app, when he presses a button, it imports that value to a webpage which also requests the user to type.
This is the flow chart or something
User --> User inputs a text in the app --> App copies what the user's typed --> App opens a particular website --> App pastes what he copied to the website.
(Website: A google form for an example.)
Now I've already finished all of it except for the latter part where the app pastes what he copied.
The problem is the app do not know where to paste it.
So I want to get the ID's of the code below, it is perfectly fine if you just identify all the id's or something similar and how to call it.
Have imported data from backend successfully, but have zero clue on how to get the id's or the variable names of a textarea, radio buttons, the div.
javascript:
(function () {
function WW(ele, val)
{
if(document.getElementById(ele) && val != "")
{
document.getElementById(ele).value = val;
}
}
WW("story-title", "The Good Peacock");
)();
Copied this from someone.
This works with other sites that have the an id, like:
<textarea id="story-title">
So, need to know the id's of the HTML below.
This is a part of the source code of the website, which is auto-fill.
Tried calling with getElementByClassName(), but didn't work.
<form class="main-edit-form">
<div class="required-form-wrapper">
<div class="form-group title-form">
<label>Title</label>
<span class="empty-warning hidden" id="title-warning">Required</span>
<div contenteditable="true" class="story-title">Untitled Story</div>
</div>
<div class="form-group description-form">
<div class="form-wrapper">
<label>Description</label>
<span data-toggle="popover" class="popover-icon" id="description-tooltip" title="" data-original-title="Add a story description"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="empty-warning hidden" id="description-warning">Required</span>
</div>
<textarea type="text" name="title" class="story-description "></textarea>
</div>
<div class="form-group tags-form">
<div class="form-wrapper">
<label>Tags</label>
<span data-toggle="popover" class="popover-icon" id="tags-tooltip" title="" data-original-title="Help readers find your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="empty-warning hidden" id="tag-empty-warning">Required</span>
</div>
<div class="tag-container">
<div id="editable-tags">
<div class="component-wrapper" id="component-TagGrid-storyTags-/myworks/new"></div>
</div>
<div id="add-tag" class="tag-item with-icon on-add-tag">
<span>Add a tag</span><span class="fa fa-plus fa-wp-black " aria-hidden="true" style="font-size:12px;"></span>
</div>
<span id="tag-input-wrapper">
<input id="tag-input" class="hidden on-tag-input" placeholder="Separate tags with a space" autocomplete="off">
</span>
</div>
</div>
<div class="form-group inline-form">
<div class="form-wrapper">
<label for="categoryselect">Genre</label>
<span data-toggle="popover" class="popover-icon" id="category-tooltip" title="" data-original-title="Tell Wattpad the genre of your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="categoryselect" class="form-control ">
<option value="-1">Select a genre</option>
<option value="14">Action</option>
<option value="11">Adventure</option>
<option value="24">ChickLit</option>
<option value="6">Fanfiction</option>
<option value="3">Fantasy</option>
<option value="21">General Fiction</option>
<option value="23">Historical Fiction</option>
<option value="9">Horror</option>
<option value="7">Humor</option>
<option value="8">Mystery / Thriller</option>
<option value="16">Non-Fiction</option>
<option value="12">Paranormal</option>
<option value="2">Poetry</option>
<option value="19">Random</option>
<option value="4">Romance</option>
<option value="5">Science Fiction</option>
<option value="17">Short Story</option>
<option value="13">Spiritual</option>
<option value="1">Teen Fiction</option>
<option value="18">Vampire</option>
<option value="22">Werewolf</option>
</select>
<span class="empty-warning hidden" id="category-empty-warning">Required</span>
</div>
</div>
</div>
<div class="inline-form-wrapper">
<div class="inline-form-row">
<div class="form-group inline-form">
<div class="form-wrapper">
<label>Language</label>
<span data-toggle="popover" class="popover-icon" id="language-tooltip" title="" data-original-title="What language is your story in?"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="languageselect" class="form-control ">
<option value="1" selected="selected">English</option>
<option value="2">Français</option>
<option value="3">Italiano</option>
<option value="4">Deutsch</option>
<option value="5">Español</option>
<option value="6">Português</option>
<option value="38">Català</option>
<option value="19">Tiếng Việt</option>
<option value="18">Filipino</option>
<option value="20">Bahasa Indonesia</option>
<option value="22">Bahasa Melayu</option>
<option value="32">ภาษาไทย</option>
<option value="7">Русский</option>
<option value="15">Română</option>
<option value="23">Türkçe</option>
<option value="24">Česky</option>
<option value="14">Polski</option>
<option value="28">Magyar</option>
<option value="30">ελληνικά</option>
<option value="35">Eesti</option>
<option value="36">Latviešu</option>
<option value="37">Lietuvių</option>
<option value="39">Босански</option>
<option value="40">Српски</option>
<option value="41">Hrvatski</option>
<option value="43">Български</option>
<option value="44">Slovenčina</option>
<option value="42">Slovenščina</option>
<option value="45">Беларускі</option>
<option value="46">Українська</option>
<option value="26">Svenska</option>
<option value="27">Norsk</option>
<option value="34">Suomi</option>
<option value="29">Dansk</option>
<option value="13">Nederlands</option>
<option value="33">Íslenska</option>
<option value="12">简体中文</option>
<option value="8">繁體中文</option>
<option value="9">日本語</option>
<option value="10">한국어</option>
<option value="16">العربية</option>
<option value="53">ગુજરાતી</option>
<option value="17">עברית</option>
<option value="21">हिन्दी</option>
<option value="25">മലയാളം</option>
<option value="54">ଓଡ଼ିଆ</option>
<option value="31">فارسی</option>
<option value="55">ਪੰਜਾਬੀ</option>
<option value="56">অসমীয়া</option>
<option value="47">বাংলা</option>
<option value="48">اُردُو‎</option>
<option value="49">தமிழ்</option>
<option value="50">Kiswahili</option>
<option value="51">Afrikaans</option>
<option value="57">मराठी</option>
<option value="11">Other</option>
</select>
</div>
</div>
<div class="form-group inline-form copyright-form">
<div class="form-wrapper">
<label>Copyright</label>
<span data-toggle="popover" class="popover-icon" id="copyright-tooltip" title="" data-original-title="Who owns your story?"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="copyrightSelect" class="form-control ">
<option value="0">Not Specified</option>
<option value="1">All Rights Reserved</option>
<option value="2">Public Domain</option>
<option value="3">Creative Commons (CC) Attribution</option>
<option value="4">(CC) Attrib. NonCommercial</option>
<option value="5">(CC) Attrib. NonComm. NoDerivs</option>
<option value="6">(CC) Attrib. NonComm. ShareAlike</option>
<option value="7">(CC) Attribution-ShareAlike</option>
<option value="8">(CC) Attribution-NoDerivs</option>
</select>
</div>
</div>
</div>
<div class="form-group rating-form">
<div class="form-wrapper">
<label class="rating-label">Rating</label>
<span data-toggle="popover" class="popover-icon" id="rating-tooltip" title="" data-original-title="Rate your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="toggle-prompt">Mature</span>
<div class="onoffswitch ">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="mature-switch">
<label class="onoffswitch-label" for="mature-switch">
<div class="onoffswitch-inner">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
<span class="onoffswitch-switch"></span>
</label>
</div>
</div>
Thank you in advance!
These id's you are looking for are not generated by them self.
You need to assign id to field that you like.
I don't prefer to use id to implement css. Element id is only to be needed to implement javascript and fetch there value example from input tag.
You need to assign id while writing down your code like in following sample html.
Point to note:
Not all tags have id.
Mostly tags related to user input have id.
No 2 elements / tag have same id.
id's of different type of elements are used for different purpose, like <div>, <span> id's are used for show-hide, where as input id's are used for fetching value.
HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/app.css" />
<link rel="icon" href="logo.jpg" />
<title>Info</title>
</head>
<body>
<div class="col-md-6 offset-md-3">
<div class="col-md-6">
<p class="btn btn-primary form-control" onclick="showForm('#addInfo')">Add Detail</p>
</div>
<div class="col-md-6">
<p class="btn btn-primary form-control" onclick="showForm('#showInfo');getDetail();">Show Detail</p>
</div>
<!-- No need for `form` as will use JavaScript for Single Page Application -->
<div id="addInfo" class="hide">
<div id="data"></div>
<div class="col-md-12 form-group">
<label for="addEmail">Email:</label>
<input id="addEmail" class="form-control" type="email">
<span id="addEmailError" class="hide error">Valid Email Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addFname">First Name:</label>
<input id="addFname" class="form-control" type="text">
<span id="addFnameError" class="hide error">Valid First Name Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addLname">Last Name:</label>
<input id="addLname" class="form-control" type="text">
<span id="addLnameError" class="hide error">Valid Last Name Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addPhone">Phone:</label>
<input id="addPhone" class="form-control" type="text">
<span id="addPhoneError" class="hide error">Valid Phone Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addGender">Gender:</label>
<select id="addGender" class="form-control">
<option value="">Select:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="addGenderError" class="hide error">Gender Required</span>
</div>
<div class="col-md-12 form-group">
<p class="btn btn-primary form-control" onclick="addInfo()">Submit</p>
</div>
</div>
<!-- No need for `form` as will use JavaScript for Single Page Application -->
<div id="showInfo" class="hide">
<div id="showDetails" class="col-md-12"></div>
</div>
</div>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<!-- `login.js` is only used in `login.ejs` -->
<script type="text/javascript" src="/js/addInfo.js"></script>
<script type="text/javascript" src="/js/getInfo.js"></script>
<script type="text/javascript" src="/js/service.js"></script>
</body>
</html>
addInfo.js:
"use strict";
function addInfo() {
// JavaScript uses `id` to fetch value
let email = $("#addEmail").val(),
fName = $("#addFname").val(),
lName = $("#addLname").val(),
phone = $("#addPhone").val(),
gender = $("#addGender").val();
// Show error `span` when email is invalid
if ( validateEmail(email) ) {
$("#addEmailError").addClass("hide");
} else {
$("#addEmailError").removeClass("hide");
return;
}
// Show error `span` when First Name is invalid
if ( validateFname(fName) ) {
$("#addFnameError").addClass("hide");
} else {
$("#addFnameError").removeClass("hide");
return;
}
// Show error `span` when Last Name is invalid
if ( validateLname(lName) ) {
$("#addLnameError").addClass("hide");
} else {
$("#addLnameError").removeClass("hide");
return;
}
// Show error `span` when Phone is invalid
if ( validatePhone(phone) ) {
$("#addPhoneError").addClass("hide");
} else {
$("#addPhoneError").removeClass("hide");
return;
}
// Show error `span` when Gender is invalid
if ( validateGender(gender) ) {
$("#addGenderError").addClass("hide");
} else {
$("#addGenderError").removeClass("hide");
return;
}
// Calling local API to set authentication
// Everything in public is visible for hackers
// Thus to hide auth calling local backend
$.ajax({
"url": "/v1/detail",
"method": "POST",
"data": {email, fName, lName, phone, gender}
})
.then( result => {
// On success empty all the input fields.
$("#addEmail").val('');
$("#addFname").val('');
$("#addLname").val('');
$("#addPhone").val('');
$("#addGender").val("");
// Message to notify success submition
alert("Successfully added user.");
return;
})
.catch( err => {
// Notify in case some error occured
alert("An error occured.");
return;
});
}
getInfo.js:
"use strict";
function getDetail () {
// Request to get details of all user.
$.ajax({
"url": "http://localhost:4000/v1/detail",
"method": "GET"
})
.then( result => {
// On success using table to display data.
// This table is dynamic.
let table = `<div class="alert alert-success" role="alert">
Details fetched successfully.
</div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>`;
let headers = [];
// Setting dynamic headers to ease work at frontend in case field changes
for ( let key in result[0] ) headers.push(key);
for ( let h of headers ) table += `<th scope="col">` + h + `</th>`;
table += ` </tr>
</thead>
<tbody>`;
let i = 1;
// Dynaic rows of table based upon headers.
for(let row of result) {
table += ` <tr>
<th scope="row">` + i + `</th>`;
for (let key of headers) table += `<td>` + row[key] + `</td>`;
table += ` </tr>`;
i++;
}
table += ` </tbody>
</table>`;
// Loading dynamic table into our static HTML page.
$("#showDetails").html(table);
})
.catch( err => {
// If error setting dynamic error
let data = `<label class="alert alert-warning">Unable to fetch details</label>`;
// Loading dynamic error into our static HTML page
$("#showDetails").html(data);
})
}
service.js:
"use strict";
/**
* Common services used by all the other scripts
* All these are generic functions
*
*/
// To toggle between different views
function showForm (id) {
// Hide all views
$("#addInfo").addClass("hide");
$("#showInfo").addClass("hide");
// Show the view user had clicked
$(id).removeClass("hide");
}
// Validate Email based upon pattern
function validateEmail (email) {
if ( email && email.match(/^([A-z0-9_.]{2,})([#]{1})([A-z]{1,})([.]{1})([A-z.]{1,})*$/) ) {
return true;
}
return false;
}
// Validate First Name based upon pattern
function validateFname (fName) {
if ( fName && fName.match(/^([A-z]{2,})*$/) ) {
return true;
}
return false;
}
// Validate Last Name based upon pattern
function validateLname (lName) {
if ( lName && lName.match(/^([A-z]{2,})*$/) ) {
return true;
}
return false;
}
// Validate Phone based upon pattern
function validatePhone (phone) {
if ( phone && phone.match(/^([0-9]{10})*$/) ) {
return true;
}
return false;
}
// Validate Gender based upon pattern
function validateGender (gender) {
if ( gender && gender.match(/^([A-z]{4,6})*$/) && (gender === "male" || gender === "female") ) {
return true;
}
return false;
}

AngularJS repeat HTML content based on Dropdown selection number

I have drop down to select a number.
Based on the selected value I need to repeat the sections in html.
For example if I choose 3 in the drop down then the page should display
Display section 1 of 3
Display section 2 of 3
Display section 3 of 3
Please help to figure out how I can achieve this. Your time and help is greatly appreciated.
Java Script:
angular.module("myApp", [])
.controller("SolutionCtrl", function SolutionCtrl() {
var vm = this;
vm.noOfSites = 0;
vm.updateSites = function() {
console.log(vm.noOfSites);
}
vm.getTimes = function(n) {
return new Array(n);
}
})
html:
<body>
<div ng-app="myApp">
<div ng-controller="SolutionCtrl as ctrl">
<div>
<h5>Select No of Sites:</h5>
<select ng-model="ctrl.noOfSites" ng-change="ctrl.updateSites()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div ng-repeat = "t in ctrl.getTimes(ctrl.noOfSites) track by $index">
<h2>Display section {{t}} of 3 </h2>
</div>
</div>
</div>
</body>
JSFiddle:
Working Fiddle: https://jsfiddle.net/mnaxp5nz/6/
HTML
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div>
<div>
<h5>Select No of Sites:</h5>
<select ng-model = "noOfSites" ng-init = "noOfSites = 0" ng-change = "updateSections();">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div ng-repeat = "section in sections">
Section {{ $index + 1 }} of {{ sections.length }}
</div>
</div>
</div>
</body>
Script
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.sections = [];
$scope.updateSections = function () {
$scope.sections = [];
for (counter = 1; counter <= $scope.noOfSites; counter++) {
$scope.sections.push(counter);
}
}
});
</script>
just add the angularjs script file in your script it is working for me
try below one:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
angular.module("myApp", [])
.controller("SolutionCtrl", function SolutionCtrl() {
var vm = this;
vm.noOfSites = 0;
vm.updateSites = function() {
console.log(vm.noOfSites);
}
vm.getTimes = function(n) {
return new Array(n);
}
})
</script>
<body>
<div ng-app="myApp">
<div ng-controller="SolutionCtrl as ctrl">
<div>
<h5>Select No of Sites:</h5>
<select ng-model="ctrl.noOfSites" ng-change="ctrl.updateSites()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div ng-repeat = "t in ctrl.getTimes(ctrl.noOfSites) track by $index">
<h2>Display section {{t}} of 3 </h2>
</div>
</div>
</div>
</body>
How about this...
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
angular.module("myApp", [])
.controller("SolutionCtrl", function SolutionCtrl() {
var vm = this;
vm.arr = [];
vm.noOfSites = 0;
vm.updateSites = function() {
for (var i = 1; i <= vm.noOfSites; i++) {
vm.arr.push(i);
}
}
vm.getTimes = function(n) {
return new Array(n);
}
})
</script>
<body>
<div ng-app="myApp">
<div ng-controller="SolutionCtrl as ctrl">
<div>
<h5>Select No of Sites:</h5>
<select ng-model="ctrl.noOfSites" ng-change="ctrl.updateSites()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div ng-repeat="t in ctrl.arr track by $index">
<h2>Display section {{t}} of 3 </h2>
</div>
</div>
</div>
</body>
You have to change in GetTimes method that return array.
Please try below.
angular.module("myApp", [])
.controller("SolutionCtrl", function SolutionCtrl() {
var vm = this;
vm.noOfSites = 0;
vm.updateSites = function() {
//console.log(vm.noOfSites);
}
vm.getTimes = function(count) {
//return new Array(n);
var ratings = [];
for (var i = 0; i < count; i++) {
ratings.push(i)
}
return ratings;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div ng-app="myApp">
<div ng-controller="SolutionCtrl as ctrl">
<div>
<h5>Select No of Sites:</h5>
<select ng-model="ctrl.noOfSites" ng-change="ctrl.updateSites()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div ng-repeat = "t in ctrl.getTimes(ctrl.noOfSites) track by $index">
<h2>Display section {{t+1}} of 3 </h2>
</div>
</div>
</div>
</body>
Try this
<div ng-app="myApp">
<div ng-controller="Ctrl as vm">
<div>
<h5>Select No of Sites:</h5>
<select ng-model="vm.noOfSites" ng-options="durations for durations in vm.stories"></select>
</div>
<div ng-repeat = "t in vm.getTimes(vm.noOfSites) track by $index" ng-show="vm.noOfSites">
<h2>Display section <span data-ng-bind="$index + 1"></span> of <span data-ng-bind="vm.stories.length"></span> </h2>
</div>
</div>
script
angular.module('myApp', [])
.controller('Ctrl', function Ctrl(){
this.stories = [1,2,3]
this.getTimes = function(n) {
if(n){
return new Array(n);
}
}
});

Filter select categories based on selected main categories (angularJS)

I'm wondering if it's possible to filter categories selector based on the first selected category in my current code and how to achieve desired effect.
This is my controller which provides all categories
controllers.addItemCtrl = function($scope, productsFactory, sessionFactory, categoriesFactory, $http, $location){
sessionFactory.isLoggedIn().then(function(data){
var loggedIn = data.logged_in;
if(loggedIn){
categoriesFactory.getCategoriesList().success(function(data){
console.log(data);
$scope.categories = data;
});
} else {
window.location.href="/#/login";
}
});
}
This is my response for categories
[{"id_category":"1","category":"Audio, video & photo","parent":"0","alias":"audio-video-and-photo","image":"" ....etc}]
And this is my HTML
<div class="form-group">
<label for="category">
<i class="icon-user"></i><b>Category</b>
</label><br>
<select name="category" id="category">
<option ng-repeat="c in categories track by $index"
ng-if="c.parent == 0"
value="{{c.id_category}}">{{c.category}}</option>
</select>
<span ng-class="{'submissionMessage' : errorDescription}"
ng-bind="errorDescription">
</span>
</div>
<div class="form-group">
<label for="subCategory">
<i class="icon-user"></i><b>Sub category</b>
</label><br>
<select name="subCategory" id="subCategory">
<option ng-repeat="c in categories track by $index"
ng-if="c.parent > 0" value="{{c.id_category}}">
{{c.category}}
</option>
</select>
<span ng-class="{'submissionMessage' : errorDescription}"
ng-bind="errorDescription"></span>
</div>
How to make a filter, Let say if I select main category Audio, video & photo with id 1, then I want in another selector show only categories with parent id 1
If you need any additional information, please let me know and I will provide.
HTML
<div ng-app="myApp" ng-controller="myCtrl">
<div class="form-group">
<label for="category"><i class="icon-user"></i><b>Category</b></label><br>
<select name="category" id="category" ng-change='searchSubCategory(parentCat)' ng-model='parentCat'>
<option ng-repeat="c in categories track by $index" ng-if="c.parent == 0" value="{{c.id_category}}">
{{c.category}}
</option>
</select>
<span ng-class="{'submissionMessage' : errorDescription}" ng-bind="errorDescription"></span>
</div>
<div class="form-group">
<label for="subCategory"><i class="icon-user"></i><b>Sub category</b></label><br>
<select name="subCategory" id="subCategory">
<option ng-repeat="c in subcategory track by $index" ng-if="c.parent > 0" value="{{c.id_category}}">
{{c.category}}
</option>
</select>
<span ng-class="{'submissionMessage' : errorDescription}" ng-bind="errorDescription"></span>
</div>
</div>
Javascript Logic
.controller('myCtrl', function($scope)
{
$scope.categories = [{"id_category":"1","category":"Audio, video & photo","parent":"0","alias":"audio-video-and-photo","image":""},{"id_category":"2","category":"Music players","parent":"1","alias":"music-players","image":""},{"id_category":"3","category":"Musical instruments","parent":"1","alias":"musical-instruments","image":""},{"id_category":"4","category":"Music accessories","parent":"1","alias":"music-accessories","image":""},{"id_category":"5","category":"Hi-Fi","parent":"1","alias":"hi-fi","image":""},{"id_category":"6","category":"Home cinema","parent":"1","alias":"home-cinema","image":""},{"id_category":"7","category":"TV's","parent":"1","alias":"tv","image":""},{"id_category":"8","category":"Rest","parent":"1","alias":"rest","image":""},{"id_category":"9","category":"Cars & bikes","parent":"0","alias":"cars-and-bikes","image":""},{"id_category":"10","category":"Whole cars","parent":"9","alias":"whole-cars","image":""},{"id_category":"11","category":"Bikes","parent":"9","alias":"bikes","image":""},{"id_category":"12","category":"Car parts","parent":"9","alias":"car-parts","image":""},{"id_category":"13","category":"Auto acoustics","parent":"9","alias":"auto-acoustics","image":""},{"id_category":"14","category":"Mobile homes, trailers and equipment","parent":"9","alias":"mobile-homes-trailers-and-equipment","image":""},{"id_category":"15","category":"Tires","parent":"9","alias":"tires","image":""},{"id_category":"16","category":"Rims","parent":"9","alias":"rims","image":""},{"id_category":"17","category":"Car accessories","parent":"9","alias":"car-accessories","image":""},{"id_category":"18","category":"Home and garden","parent":"0","alias":"home-and-garden","image":""},{"id_category":"19","category":"Construction and installation","parent":"18","alias":"construction-and-installation","image":""},{"id_category":"20","category":"Refrigerators & Freezers","parent":"18","alias":"refrigerators-and-freezers","image":""},{"id_category":"21","category":"Cooking and kitchen utensils","parent":"18","alias":"cooking-and-kitchen-utensils","image":""},{"id_category":"22","category":"Home equipment","parent":"18","alias":"home-equipment","image":""},{"id_category":"23","category":"Tools and machines","parent":"18","alias":"tools-and-machines","image":""},{"id_category":"24","category":"furniture","parent":"18","alias":"furniture","image":""},{"id_category":"25","category":"cleaning and washing machines","parent":"18","alias":"cleaning-and-washing-machines","image":""},{"id_category":"26","category":"Garden and working equipment","parent":"18","alias":"garden-and-working-equipment","image":""},{"id_category":"27","category":"Pets and accessories","parent":"18","alias":"pets-and-accessories","image":""},{"id_category":"28","category":"Camera","parent":"1","alias":"camera","image":""},{"id_category":"29","category":"Beauty and health","parent":"0","alias":"0","image":""},{"id_category":"30","category":"Personal care appliances","parent":"29","alias":"personal-care-appliances","image":""},{"id_category":"31","category":"Appliances for health","parent":"29","alias":"appliances-for-health","image":""},{"id_category":"32","category":"Cosmetics and hygiene","parent":"29","alias":"cosmetics-and-hygiene","image":""},{"id_category":"33","category":"Makeup","parent":"29","alias":"makeup","image":""},{"id_category":"34","category":"Jewellery","parent":"29","alias":"jewellery","image":""},{"id_category":"35","category":"Glasses","parent":"29","alias":"glasses","image":""},{"id_category":"36","category":"Perfumes","parent":"29","alias":"perfumes","image":""},{"id_category":"37","category":"Rest","parent":"18","alias":"rest","image":""},{"id_category":"38","category":"Rest","parent":"9","alias":"rest","image":""},{"id_category":"39","category":"Hand watches","parent":"29","alias":"hand-watches","image":""},{"id_category":"40","category":"Clothing","parent":"0","alias":"clothing","image":""},{"id_category":"41","category":"Women's clothing","parent":"40","alias":"womens-clothing","image":""},{"id_category":"42","category":"Men's clothing","parent":"40","alias":"mens-clothing","image":""},{"id_category":"43","category":"Kid's clothing","parent":"40","alias":"kids-clothing","image":""},{"id_category":"44","category":"Fashion accessories","parent":"40","alias":"fashion-accessories","image":""},{"id_category":"45","category":"Rest","parent":"40","alias":"rest","image":""},{"id_category":"46","category":"Books and literature","parent":"82","alias":"books-and-literature","image":""},{"id_category":"47","category":"Office equipment","parent":"82","alias":"office-equipment","image":""},{"id_category":"48","category":"Office Furniture","parent":"82","alias":"office-furniture","image":""},{"id_category":"49","category":"School","parent":"82","alias":"school","image":""},{"id_category":"50","category":"Rest","parent":"82","alias":"rest","image":""},{"id_category":"51","category":"Computers","parent":"0","alias":"computers","image":""},{"id_category":"52","category":"Laptops","parent":"51","alias":"laptops","image":""},{"id_category":"53","category":"Stationary computer","parent":"51","alias":"stationary-computer","image":""},{"id_category":"54","category":"Tablets","parent":"51","alias":"tablets","image":""},{"id_category":"55","category":"Computer components","parent":"51","alias":"computer-components","image":""},{"id_category":"56","category":"Computer equipment","parent":"51","alias":"computer-equipment","image":""},{"id_category":"57","category":"Network","parent":"51","alias":"network","image":""},{"id_category":"58","category":"Printers & scanners","parent":"51","alias":"printers-and-scanners","image":""},{"id_category":"59","category":"Cartridges and toners","parent":"51","alias":"cartridges-and-toners","image":""},{"id_category":"60","category":"Rest","parent":"51","alias":"rest","image":""},{"id_category":"61","category":"Sport","parent":"0","alias":"sport","image":""},{"id_category":"62","category":"Outdoor & camping","parent":"61","alias":"outdoor-and-camping","image":""},{"id_category":"63","category":"Modelling","parent":"61","alias":"modelling","image":""},{"id_category":"64","category":"Racquet Sports","parent":"61","alias":"racquet-sports","image":""},{"id_category":"65","category":"Cycling","parent":"61","alias":"cycling","image":""},{"id_category":"66","category":"Fitness & aerobics","parent":"61","alias":"Fitness-and-aerobics","image":""},{"id_category":"67","category":"Hiking & climbing","parent":"61","alias":"Hiking-and-climbing","image":""},{"id_category":"68","category":"Skiing","parent":"61","alias":"skiing","image":""},{"id_category":"69","category":"GPS, watches and gauges","parent":"61","alias":"Gps-watches-and-gauges","image":""},{"id_category":"70","category":"Rest","parent":"61","alias":"rest","image":""},{"id_category":"71","category":"Phones","parent":"0","alias":"phones","image":""},{"id_category":"72","category":"Gsm","parent":"71","alias":"gsm","image":""},{"id_category":"73","category":"Gsm accessories","parent":"71","alias":"gsm-accessories","image":""},{"id_category":"74","category":"Rest","parent":"71","alias":"rest","image":""},{"id_category":"75","category":"Kids","parent":"0","alias":"kids","image":""},{"id_category":"76","category":"Car seats","parent":"75","alias":"car-seats","image":""},{"id_category":"77","category":"Prams","parent":"75","alias":"prams","image":""},{"id_category":"78","category":"Baby equipment and accessories","parent":"75","alias":"Baby-equipment-and-accessories","image":""},{"id_category":"79","category":"Toys","parent":"75","alias":"toys","image":""},{"id_category":"80","category":"Children's playgrounds","parent":"75","alias":"childrens-playground","image":""},{"id_category":"81","category":"Rest","parent":"29","alias":"rest","image":""},{"id_category":"82","category":"Books & Office material","parent":"0","alias":"books-and-office-material","image":""},{"id_category":"83","category":"Rest","parent":"75","alias":"rest","image":""},{"id_category":"84","category":"Bike accessories","parent":"9","alias":"bike-accessories","image":""}];
$scope.searchSubCategory = function(parentCat)
{
$scope.subcategory = [];
for(i=0;i<$scope.categories.length;i++)
{
if(parentCat==$scope.categories[i].parent)
{
$scope.subcategory.push($scope.categories[i])
}
}
}
});
Create simple function when selected index change and do some little logic

Get HTML attribute values using jQuery

<html>
<body>
<div class="block-a">
<label data-value="15" name=symptom">Group1</label>
<div class="clsfWrapper">
<label data-value="10" name=clsfName"> SubHeader1</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
<div class="clsfWrapper">
<label data-value="11" name=clsfName"> SubHeader2</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
</div>
<div class="block-a">
<label data-value="16" name=symptom">Group2</label>
<div class="clsfWrapper">
<label data-value="5" name=clsfName"> SubHeader1</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
<div class="clsfWrapper">
<label data-value="6" name=clsfName"> SubHeader2</label>
<div class="ui-select">
<div class="ui-btn">
<span>SelectedValue</span>
<select class="selectClass">
<option value="1">value1</option>
<option value="2">value2</option>
<option value="3">value3</option>
</select>
</div>
</div>
</div>
</div>
</html>
</body>
What is the best way to find every select SubHeader and Group value? For example the first one:
Group value: 15
Subheader value: 10
Option value : 1
and second one:
Group value: 15
Subheader value: 11
Option value : 1
I have a very robust way to get those values and i was wondering if there was any easier and more certain way.
jQuery:
function getHtmlAttributes(){
$.each($('#page_visit_reg_new_colds_2 option:selected'), function(key, value){
var optionParent = $(this).parent();
var selectParent = optionParent.parent();
var divParent1 = selectParent.parent();
var divParent2 = divParent1.parent();
var subheaderName = divParent1.parent().find('label[name=clsfName]').data('value');
var groupName = divParent2.parent().find('label[name=symptom]').data('value');
});
EDIT Changed label value to data-value
This instead of going from the option and then with parent up to the group, will start from the block and go down to the selected option.
It is still cycling trough the elements but is not using parent()
$.each($('.block-a'), function(){
var groupName = $(this).find("label[name='symptom']").data('value');
$.each($(this).find(".clsfWrapper"), function(){
var subheaderName = $(this).find("label[name='clsfName']").data('value');
$.each($(this).find('select option:selected'), function(){
var optionvalue = $(this).val();
});
});
});
On the JSFiddle i've added console log so you can check if everything is what you expect.
Since you're using the data attribute, just use this jQuery syntax:
$("#elementName").data("DataAttribute");
To get the value from the following label (IDs are better than names):
<label data-value="11" id="clsfName"> SubHeader2</label>
Use this:
var dataValue = $("#clsfName").data("value");

Categories