trying to use ngSwitch in angular - angularjs

I'm testing the following code in angular and it's not working. I'm very new to Angular and I've been unable to figure this out. All I'm trying to do is show a particular element based on a step number when next/back buttons are clicked.
<div ng-app ng-controller="Ctrl">
<div ng-switch on="selection" >
<div ng-switch-when="2" step-number="2">Settings Div</div>
<span ng-switch-when="1" step-number="1">Home Span</span>
<span ng-switch-default step-number="3">default</span>
<button ng-click="back(step-number)">back</button>
<button ng-click="forward(step-number)">forward</button>
</div>
</div>
function Ctrl($scope) {
$scope.items = ['1', '2', '3'];
$scope.forward = function($selected) { $scope.selection = $scope.items[$selected - 1]; };
$scope.back = function($selected) { $scope.selection = $scope.items[$selected - 1]; };
}

I think I would refactor what you are doing to the following:
Demo: http://plnkr.co/edit/b7mQ5ssSqECDUhvN0S2b?p=preview (click back first).
app.controller('Ctrl', function($scope) {
$scope.name = 'World';
$scope.selection = 2;
$scope.items = ['div 1', 'div 2', 'div 3'];
$scope.forward = function() {
if ($scope.selection==$scope.items.length-1) $scope.selection=0;
else $scope.selection++;
};
$scope.back = function() {
if ($scope.selection==0) $scope.selection = $scope.items.length-1;
else $scope.selection --;
};
});
<body ng-controller="Ctrl">
<div >
<div>
<div>{{items[selection]}}</div>
<button ng-click="back()">back</button>
<button ng-click="forward()">forward</button>
</div>
</div>
</body>

I'm not sure what you are trying to do with step-number, but here is a way to make your buttons work between the values of 1 and 3 inclusive:
<div ng-switch on="selection">
<div ng-switch-when="2">Settings Div</div>
<span ng-switch-when="1">Home Span</span>
<span ng-switch-default step-number="3">default</span>
<button ng-click="back()">back</button>
<button ng-click="forward()">forward</button>
</div>
function MyCtrl($scope) {
$scope.selection = 3;
$scope.forward = function () {
$scope.selection += 1;
if ($scope.selection > 3) $scope.selection = 3;
console.log($scope.selection);
};
$scope.back = function () {
$scope.selection -= 1;
if ($scope.selection < 1) $scope.selection = 1;
console.log($scope.selection);
};
}
fiddle

Related

Assign dynamic ng-model in a template for radio buttons

I use a directive to add images and radio buttons (per image). I also create dynamically ng-models. Now with my approach, the radio buttons will not be set. What's wrong? Thank your for your hints.
JS
.directive('oct', function() {
return {
restrict : 'E',
template : `
<div class="oImg" ng-repeat="image in images">
<a href="#" class="removeImage" ng-click="vm.removeImg(image)"
ng-show="isActive($index)"><i class="fa fa-trash"></i>
</a>
<img ng-src="{$image.src$}" class="images-item"
ng-show="isActive($index)"><span ng-show="isActive($index)" class="imgName">{$image.name$}</span>
<div class="sideSelect" ng-show="isActive($index)">
<div class="checkbox"><label>
<input type="radio" ng-model="eyeChanger[image.name]"
name="optionsEye"
ng-change="vm.changeEye(image, eyeChanger[image.name])"
value="RA">RA</label>
</div>
<div class="checkbox"><label>
<input type="radio" ng-model="eyeChanger[image.name]"
ng-change="vm.changeEye(image, eyeChanger[image.name])"
name="optionsEye" value="LA">LA</label>
</div>
</div>
</div>
`,
controller : ['$scope', '$http',
function($scope, $http) {
$scope._Index = 0;
// if current image is same as requested image
$scope.isActive = function(index) {
return $scope._Index === index;
};
// prev image
$scope.showPrev = function() {
if ($scope._Index != 0) {
$scope._Index = ($scope._Index > 0) ? --$scope._Index : $scope.images.length - 1;
}
};
// next image
$scope.showNext = function() {
if ($scope._Index < $scope.images.length - 1) {
$scope._Index = ($scope._Index < $scope.images.length - 1) ? ++$scope._Index : 0;
};
};
}]
};
})
vm.changeEye = function(img, value) {
$scope['eyeChanger'+img.name] = value;
...
Use:
vm.changeEye = function(img, value) {
̶$̶s̶c̶o̶p̶e̶[̶'̶e̶y̶e̶C̶h̶a̶n̶g̶e̶r̶'̶+̶i̶m̶g̶.̶n̶a̶m̶e̶]̶ ̶=̶ ̶v̶a̶l̶u̶e̶;̶
$scope.eyeChanger[img.name] = value;
...
There is no need to do this with ng-change as the ng-model directive does it automatically.
<div ng-repeat="image in images">
<img ng-src="{{image.src}}" />
<div class="checkbox"><label>
<input type="radio" ng-model="eyeChanger[image.name]"
name="optionsEye"
̶n̶g̶-̶c̶h̶a̶n̶g̶e̶=̶"̶v̶m̶.̶c̶h̶a̶n̶g̶e̶E̶y̶e̶(̶i̶m̶a̶g̶e̶,̶ ̶e̶y̶e̶C̶h̶a̶n̶g̶e̶r̶[̶i̶m̶a̶g̶e̶.̶n̶a̶m̶e̶]̶)̶"̶
value="RA">RA</label>
</div>
<div class="checkbox"><label>
<input type="radio" ng-model="eyeChanger[image.name]"
̶n̶g̶-̶c̶h̶a̶n̶g̶e̶=̶"̶v̶m̶.̶c̶h̶a̶n̶g̶e̶E̶y̶e̶(̶i̶m̶a̶g̶e̶,̶ ̶e̶y̶e̶C̶h̶a̶n̶g̶e̶r̶[̶i̶m̶a̶g̶e̶.̶n̶a̶m̶e̶]̶)̶"̶
name="optionsEye" value="LA">LA</label>
</div>
</div>
The radio buttons can be initialized:
$scope.images = [
{ name: "name1", src: "..." },
{ name: "name2", src: "..." },
// ...
];
$scope.eyeChanger = {
name1: "RA",
name2: "LA",
// ...
};

Get the value of dynamic check boxes in angular js when submitting the form

In my HTML form there are 5 check boxes. How can I check which check boxes are checked or not at the time of the form submission?
I am using this little piece of code. Feel free to take it.
In your controller:
$scope.sentinel = [];
$scope.toggleSelection = function(value) {
// Bit trick, equivalent to "contains"
if (~$scope.sentinel.indexOf(value)) {
var idx = $scope.sentinel.indexOf(value);
$scope.sentinel.splice(idx, 1);
return;
}
$scope.sentinel.push(value);
};
Then in your HTML:
<span ng-repeat="key in $scope.yourarray">
<md-checkbox style="margin-left:30px;" aria-label="Select item"
ng-click="toggleSelection(key)"><span>{{ key }}</span></md-checkbox>
<br/>
</span>
This allows you to have an array of any size and using the sentinel array to register already checked values. If you check again a box, the toogleSelection will prevent you from adding again a value.
You can use the Checklist-model of Angular.js. It is very useful:
var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkAll = function() {
$scope.user.roles = angular.copy($scope.roles);
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
};
$scope.showCheckedOnes = function() {
var checkedBoxes = "";
for (var i = 0; i < $scope.user.roles.length; i++) {
checkedBoxes += $scope.user.roles[i] + " ";
}
alert(checkedBoxes);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://vitalets.github.io/checklist-model/checklist-model.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl1">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
</label>
<div>
<div>
<button ng-click="checkAll()" style="margin-right: 10px">Check all</button>
<button ng-click="uncheckAll()" style="margin-right: 10px">Uncheck all</button>
<button ng-click="checkFirst()" style="margin-right: 10px">Check first</button>
<button ng-click="showCheckedOnes()" style="margin-right: 10px">Show checked ones</button>
You can define the array value and map to html.
$scope.checkbox = [];
HTML
<input ng-model="checkbox[0] type="checkbox" />
<input ng-model="checkbox[1] type="checkbox" />
<input ng-model="checkbox[2] type="checkbox" />
<input ng-model="checkbox[4] type="checkbox" />
Or you can define checkbox as object and change checkbox[index] to checkbox[name].

Angular JS: update controller when data change in second controller

what i m doing:
simple html file shows first page , in this page i have one title and button, initially i set $scope.index = 0. so, we set first position of array. when we click on next button it finds firstCtrl and first.html page. in this controller i update $scope.index by 1. so, my question is when i update $scope.index of myCtrl then $scope.index is changed on another controller i wants to change myCtrl. is it possible ? if it is then help me.
index.html:
<body ng-controller="myCtrl">
<div id="navbar">
<div class="setToggle">
<input id="slide-sidebar" type="checkbox" role="button" />
<label for="slide-sidebar"><span class="glyphicon glyphicon-menu-hamburger"></span></label>
</div>
<div class="setQuestion">
<h2>{{surveys[index].questionTitle}}</h2>
</div>
</div>
<div class="content-wrapper" class="container-fluid">
<div class="sidebar-left">
<div class="first">
<ul ng-repeat="cat in surveys[index].category" class="list-unstyled" ng-hide="checkSubCategoryValueIsNull.length">
<li class="category">
<a ng-click="expand=!expand">
<span class="glyphicon" ng-class="{'glyphicon-plus': !expand, 'glyphicon-minus': expand}">
{{cat.categoryName}}
</span>
</a>
</li>
<ul ng-repeat="subcategory in cat.categoryItemDto" class="list-unstyled">
<li ng-show="expand">
<label class="label-style-change">
<input type="checkbox" ng-click="toggleSelectionCheckbox(surveys[index], subcategory)" ng-model="subcategory.selectValue" ng-disabled="disableCheckbox">
<span class="subcategory-item" ng-disabled="disableCheckbox">{{subcategory.subCategoryName}}</span>
</label>
</li>
</ul>
</ul>
</div>
<div class="second">
<input type="button" name="Submit" value="Submit" ng-click="submitSelection()" ng-hide="hideSubmitButton" ng-disabled="!selections[index].length">
<input type="button" name="Edit" value="Edit" ng-click="EditSelection()" ng-show="hideEditButton">
</div>
</div>
<div class="portfolio">
<div id="main">
<div ng-view></div>
</div>
</div>
</div>
</body>
controller.js
(function() {
var app = angular.module("app.controllers", ["app.service"]);
app.controller("myCtrl", ["$scope", "$http", "$location", "$timeout", "surveyService", "Data",
function ($scope, $http, $location, $timeout, surveyService, Data) {
surveyService.getData(function(dataResponse) {
$scope.surveys = dataResponse;
$scope.selections = [];
/* create 2d array mannually */
var numInternalArrays = $scope.surveys.length;
for (var i = 0; i < numInternalArrays; i++) {
$scope.selections[i] = [];
};
$scope.index = 0;
var toggleCheckboxFlag = 0;
/* PRIVATE FUNCTION
for find value from selections array and replace it
*/
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
array.splice(index, 1);
toggleCheckboxFlag = 1;
}
});
}
$scope.toggleSelectionCheckbox = function (QuestionId, value) {
toggleCheckboxFlag = 0;
if (!value) return;
findAndRemove($scope.selections[$scope.index], 'categoryId', value.subCategoryId);
if (toggleCheckboxFlag != 1) {
$scope.selections[$scope.index].push({
questionId: QuestionId.questionId,
categoryId: value.subCategoryId,
categoryName: value.subCategoryName,
storeId: 1,
comment: ""
});
}
};
$scope.submitSelection = function() {
$scope.value = $scope.selections[$scope.index];
$scope.hideSubmitButton = true;
$scope.disableCheckbox = true;
$scope.hideEditButton = true;
$location.path("/question/1");
}
});
$scope.EditSelection = function() {
$scope.hideEditButton = false;
$scope.hideSubmitButton = false;
$scope.disableCheckbox = false;
$scope.value = false;
}
$scope.$watch('index', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setIndex(newValue);
});
console.log("controller", Data.getIndex())
}]);
})();
app.js
var app = angular.module('app', ['ngRoute','app.service', 'app.controllers']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/question/1', {
templateUrl: 'views/first.html',
controller: 'sidebarCtrl'
})
.when('/question/2', {
templateUrl: 'views/second.html',
controller: 'mainCtrl'
})
.otherwise({
redirectTo: '/'
});
}]);
first.html
<div id="content-wrapper" ng-show="value">
<div class="col-lg-offset-1 col-lg-8 col-md-12 col-sm-12 col-xs-12">
<h2 class="subCategoryLabel"><span class="label">{{value[inc].categoryName}}</span></h2>
</div>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="inc == 0" ng-click="prev()">
<i class="glyphicon glyphicon-menu-left"></i>
</button>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<form name="myForm">
<div ng-repeat="item in surveys[index].optionCategoryItemDto" class="formStyle">
<label class="text-center">
<input type="radio" name="radio" id="{{item.itemId}}" ng-value="item.itemId" ng-model="selections[index][inc].answer" required>
{{item.itemName}}
</label>
</div>
<br/>
<br/>
</form>
</div>
<div class="col-lg-3 col-lg-offset-1 col-md-offset-1 col-md-3 col-sm-4 col-xs-4">
<button class="btnNext" ng-hide="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="next()">
<i class="glyphicon glyphicon-menu-right"></i>
</button>
<button class="btnNext" ng-show="selections[index].length == inc + 1" ng-disabled="myForm.radio.$error.required" ng-click="nextQuestion()">
<i class="glyphicon glyphicon-forward"></i>
</button>
</div>
</div>
<div class="col-lg-offset-3 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-4">
<textarea type="text" id="text" class="form-control txtArea" ng-model="selections[index][inc].comment" placeholder="Write comment..."></textarea>
</div>
</div>
sidebarCtrl.js
in this controller i update $scope.index when we call nextQuestion(). here $scope.index increment by one and $watch function also get latest value of index. but myCtrl is not update. i wants to update myCtrl.
(function() {
var app = angular.module("app.controllers");
app.controller("sidebarCtrl", ['$scope', "$location", "Data", function($scope, $location, Data) {
$scope.inc = 0;
$scope.next = function() {
$scope.inc += 1;
}
$scope.prev = function() {
$scope.inc -= 1;
}
$scope.nextQuestion = function() {
$scope.index += 1;
$location.path("/question/2");
}
$scope.$watch('index', function (newValue, oldValue) {
console.log("SASAS", newValue)
if (newValue !== oldValue) Data.setIndex(newValue);
});
}]);
})();
service.js
(function() {
var app = angular.module("app.service", []);
app.service("surveyService", function($http) {
this.getData = function (callbackFunc) {
$http({
method: "GET",
data: {something: true},
contentType: 'application/json',
dataType: 'jsonp',
url: "http://localhost:8080/TheSanshaWorld/sfcms/fetch-survey-details"
}).success(function(data){
callbackFunc(data);
}).error(function(){
alert("error");
});
};
this.setData = function(value) {
if (confirm('Do you wanna to submit?')) {
$http.post("http://localhost:8080/TheSanshaWorld/sfcms/save-survey-result-data", value).success(function(data, status) {
window.open("../index.html","_self");
});
} else {
return false;
}
};
});
app.factory('Data', function () {
var data = {
Index: ''
};
return {
getIndex: function () {
return data.Index;
},
setIndex: function (index) {
data.Index = index;
console.log("service", data.Index)
}
};
});
})();
Because sidebarCtrl is nested within myCtrl, therefore you can reach myCtrl $scope.index from sidebarCtrl using it $scope.$parent.index,
Try it by test: add any parameter value to myCtrl $scope.name='Bob';
then log it in sidebarCtrl console.log($scope.$parent.name); you should see printed 'Bob'. Do the same with index.

how to make dynamic 5 star rating using angularjs?

I have 3 Questions each i have given 5 stars,after user submit i need to convert to 5 how to do this using this formula x1w1 + x2w2 + x3w3 ... xnwn/Total.
http://help.surveymonkey.com/articles/en_US/kb/What-is-the-Rating-Average-and-how-is-it-calculate.i have done something but its not right way i think so?
//--------------------------------------review controller--------------
.controller('ReviewCtrl', [
'$scope', '$http', '$location', '$window',
function($scope, $http, $location, $window) {
$scope.rating1 = {};
$scope.rating2 = {};
$scope.rating3 = {};
$scope.isReadonly = true;
$scope.rateFunctionone = function(rating) {
window.localStorage.setItem("rating1", rating);
};
$scope.rateFunctiontwo = function(rating) {
window.localStorage.setItem("rating2", rating);
};
$scope.rateFunctionthree = function(rating) {
window.localStorage.setItem("rating3", rating);
};
$scope.submit = function() {
var bookingid= window.localStorage.getItem("reviewbookingid");
var storeid = window.localStorage.getItem("reviewstoreid");
var cusname = window.localStorage.getItem("username").replace(/\"/g, "");
var rating1 = window.localStorage.getItem("rating1");
var rating2 = window.localStorage.getItem("rating2");
var rating3 = window.localStorage.getItem("rating3");
var totrating = (parseInt(rating1) + parseInt(rating2) + parseInt(rating3)) / 15;
console.log(totrating);
$http.get('******').success(function(data, response) {
var totcustomer = data.length + 1;
var totcustreview =data.length;
console.log(totcustreview);
if (data.length == 0) {
var caltotrating = (0 + totrating) / totcustomer;
} else
{
var caltotrating = (parseInt(data[0].Rating) + parseInt(totrating)) / totcustomer;
}
var credentials = {};
credentials = {
"Customet_Name": cusname,
"Timely_delivery": rating1,
"Quality_of_service": rating2,
"Value_for_money": rating3,
"Average": totrating,
"Rating": caltotrating,
"Comments": $scope.command,
"Booking_id": bookingid,
"Store_id": storeid
}
var scredentials = {};
scredentials = {
"S_Ratings": caltotrating,
"S_Noofpeoplegivenreview": totcustomer,
}
$http.put('***').success(function(data, status, headers, config, response) {
});
$http.post('***').success(function(data, status, headers, config, response) {
});
});
}
}
])
//---------------------------------------------------------------------
.directive("starRating", function() {
return {
restrict: "EA",
template: "<ul class='rating' ng-class='{readonly: readonly}'>" +
" <li ng-repeat='star in stars' ng-class='star' ng-click='toggle($index)'>" +
" <i class='ion-star'></i>" + //&#9733
" </li>" +
"</ul>",
scope: {
ratingValue: "=ngModel",
max: "=?", //optional: default is 5
onRatingSelected: "&?",
readonly: "=?"
},
link: function(scope, elem, attrs) {
if (scope.max == undefined) {
scope.max = 5;
}
function updateStars() {
scope.stars = [];
for (var i = 0; i < scope.max; i++) {
scope.stars.push({
filled: i < scope.ratingValue
});
}
};
scope.toggle = function(index) {
if (scope.readonly == undefined || scope.readonly == false) {
scope.ratingValue = index + 1;
scope.onRatingSelected({
rating: index + 1
});
}
};
scope.$watch("ratingValue", function(oldVal, newVal) {
if (newVal) {
updateStars();
}
});
}
};
})
<ion-content ng-controller="ReviewCtrl" >
<form data-ng-submit="submit()">
<div class="row">
<div class="col item item-divider">Timely Delivery </div>
<div class="col item item-divider">
<div star-rating ng-model="rating1" max="5" on-rating-selected="rateFunctionone(rating)"></div>
</div>
</div>
<br>
<div class="row">
<div class="col item item-divider">Quality of Service </div>
<div class="col item item-divider">
<div star-rating ng-model="rating2" max="5" on-rating-selected="rateFunctiontwo(rating)"></div>
</div>
</div>
<br>
<div class="row">
<div class="col item item-divider"> Value for Money </div>
<div class="col item item-divider">
<div star-rating ng-model="rating3" max="5" on-rating-selected="rateFunctionthree(rating)"></div>
</div>
</div>
<br>
<ul >
<li class="item item-checkbox">
<label class="checkbox checkbox-energized">
<input type="checkbox" ng-model="recommend" ng-true-value="'yes'" ng-false-value="'no'">
</label>
Would you recommend this dealer to your friends?
</li>
</ul>
<label class="item item-input item-floating-label" >
<span class="input-label">Say! how you feel</span>
<textarea placeholder="Say! how you feel" rows="4" ng-model="command"></textarea>
</label>
<div class="padding">
<button class="button button-full button-stable" type="submit" > Submit
</button>
</form>
</div>
</ion-content>
Use this RateIt for rating its quite easy you just need bower to install it and include the js and css.

Angularfire remove items by checkbox

I am using Angularfire and I'd like to remove the items by checkbox.
And there is a button that can do the "checkAll" and another do the "uncheckAll"
HTML
<div ng-app="app" ng-controller="Ctrl">
<li ng-repeat="item in newslist">
<input type="checkbox"> {{item.newsTitle}}
</li>
<br>
<button ng-click="checkAll()">check all</button>
<button ng-click="uncheckAll()">uncheck all</button>
<button ng-click="newslist.$remove(item)">Remove</button>
</div>
JS
var app = angular.module("app", ["firebase"]);
app.value('newsURL', 'https://XXX.firebaseio.com/XXX/');
app.factory('newsFactory', function($firebase, newsURL) {
return $firebase(new Firebase(newsURL)).$asArray();
});
app.controller('Ctrl', function($scope, $firebase, newsFactory) {
$scope.newslist = newsFactory;
$scope.checkAll = function() {
};
$scope.uncheckAll = function() {
};
});
plunker here
I don't know how to remove the items by checkbox or how to make the "checkAll" button work.
I will be appreciate if someone could tell me your answer.
Here is function you would need to check/uncheck and for removing items:
$scope.checkAll = function() {
$scope.newslist.forEach(function(el) {
el.checked = true;
$scope.newslist.$save(el);
});
};
$scope.uncheckAll = function() {
$scope.newslist.forEach(function(el) {
el.checked = false;
$scope.newslist.$save(el);
});
}
$scope.remove = function() {
$scope.newslist.forEach(function(item) {
if (item.checked) {
$scope.newslist.$remove(item);
}
});
};
Demo: http://plnkr.co/edit/GsGVsGGjNwW4i1kTOuko?p=preview
I added checked property for ngModel directive.
HTML becomes:
<li ng-repeat="item in newslist">
<input type="checkbox" ng-model="item.checked">{{item.newsTitle}}
</li>
<button ng-click="checkAll()">check all</button>
<button ng-click="uncheckAll()">uncheck all</button>
<button ng-click="remove()">Remove</button>

Resources