I was working on AngularJS and trying to load products using.
$scope.update=function(){
$scope.loading = true;
$scope.brandString=$scope.brands.join(':');
UpdateService.getProducts($scope).then(function (data) { $scope.loading = false; $scope.products = data.Products;}, function () {
});
};
$scope.changepage=function(pagenum){
$scope.pagenumber=pagenum;
$scope.update();
};
$scope.changeorderby=function(orderby){
$scope.orderby=orderby;
$scope.pagenumber=1;
$scope.update();
};
$scope.updatebrands=function(id){
var index = $scope.brands.indexOf(id);
// Add if checked
if ($('#'+id).is(':checked')) {
if (index === -1) $scope.brands.push(id);
}
// Remove if unchecked
else {
if (index !== -1) $scope.brands.splice(index, 1);
}
$scope.update();
};
My 2nd and 3rd function i.e changepage and changeorderby is working properly and updating view as well. 4th function which is being called on checkbox change also return proper data from server but doesn't update my view.
Code fo checkboxes.
<div class="listbox">
<ul>
<div ng-class="{active : item.Checked, inactive:!item.Checked}" ng-repeat="item in brandDetails" style="padding:1px 0">
<div ng-class="{divchecked : item.Checked, divunchecked:!item.Checked}">
<input type="checkbox" id="{{item.Id}}" ng-change="updatebrands(item.Id)" ng-model="item.Checked" name="{{item.Name}}" value="{{item.Id}}" style="opacity:0" class="brandName ng-pristine ng-valid" /></input>
</div>
<span style="margin-left: 8px; font-size: 11px;top: -1px;position: relative;">{{item.Name}}</span>
</div>
</ul>
</div>
What I am missing here?
if UpdateService.getProducts() dosen't use raw angular $http service, then angular won't know something has happend, so you need to call $scope.$apply()
$scope.update = function(){
$scope.loading = true;
$scope.brandString = $scope.brands.join(':');
UpdateService.getProducts($scope).then(function (data) {
$scope.loading = false;
$scope.products = data.Products;
// Only if UpdateService.getProducts isn't pure $http or $q service
$scope.$apply();
}, function () {
// error
});
};
$scope.changepage = function(pagenum){
$scope.pagenumber = pagenum;
$scope.update();
};
$scope.changeorderby = function(orderby){
$scope.orderby = orderby;
$scope.pagenumber = 1;
$scope.update();
};
$scope.updatebrands = function(item){
var index = $scope.brands.indexOf(item.id);
// Add if checked
if (item.Checked) {
if (index === -1) $scope.brands.push(item.id);
}
// Remove if unchecked
else {
if (index !== -1) $scope.brands.splice(index, 1);
}
$scope.update();
};
<div class="listbox">
<ul>
<li>
<div ng-class="{active : item.Checked, inactive: !item.Checked}" ng-repeat="item in brandDetails" style="padding: 1px 0">
<div ng-class="{divchecked : item.Checked, divunchecked: !item.Checked}">
<input type="checkbox" id="{{item.Id}}" ng-change="updatebrands(item)" ng-model="item.Checked" name="{{item.Name}}" style="opacity: 0" class="brandName ng-pristine ng-valid" />
</div>
<span style="margin-left: 8px; font-size: 11px; top: -1px;position: relative;">{{item.Name}}</span>
</div>
</li>
</ul>
</div>
(BTW your code has still several problems.)
(Provide a small example code plunkr or jsfiddle to help us help you, mock your xhr response data so we know what the results will be)
Related
I'm fairly new in Javascript/AngularJS and want to play around with it to learn/understand these languages. On the Angular website there's a little basic to do list script I want to change a little. I've changed it into a checklist of things I need to learn. When i check the checkbox I got a little msg like, 'well done!'. But when I uncheck it, the same msg pops up and that I want to change in something like, 'you sure?'.
I've spent several hours on looking for the answer but couldn't find the answer so I hope someone can help me figuring out how to do this. This is my code:
HTML:
<div ng-controller="TodoListController as todoList">
<span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
<!--[ archive ]-->
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<label class="checkbox">
<input type="checkbox" onclick="alert('Well done!')" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
</div> <!--einde ng-controller -->
AngularJS code:
todoList.remaining = function() {
var count = 0;
angular.forEach(todoList.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
todoList.archive = function() {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
If there's missing something, let me know!
Thanks in advance!
Here's the updated code for you:
<div ng-controller="TodoListController as todoList">
<span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
<!--[ archive ]-->
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<label class="checkbox">
<input type="checkbox" onclick="showAlert(todo.done)" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
</div> <!--einde ng-controller -->
AngularJs Code:
todoList.remaining = function() {
var count = 0;
angular.forEach(todoList.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.showAlert = function(isSuccess){
if(isSuccess)
alert('Well done!')
else
alert('Unchecked')
};
todoList.archive = function() {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
I have several checkboxes dynamicaly generated from array source:
/*js*/
$scope.arrondissements = JSON.parse('
[{"name":"4e","checked":false,"disable":true},
{"name":"5e","checked":false,"disable":false},
{"name":"11e","checked":false,"disable":false},
{"name":"12e","checked":false,"disable":false},
{"name":"13e","checked":false,"disable":false},
{"name":"14e","checked":false,"disable":false},
{"name":"15e","checked":false,"disable":false},
{"name":"16e","checked":false,"disable":false},
{"name":"17e","checked":false,"disable":false},
{"name":"18e","checked":false,"disable":false},
{"name":"19e","checked":false,"disable":false},
{"name":"20e","checked":false,"disable":false}]');
<!-- HTML -->
<div ng-repeat="item in arrondissements" class="checkbox-inline ">
<label>
<input type="checkbox" ng-disabled="{{item.disable == true}}"
value="{{item.checked}}" ng-model="item.checked" >
<span>{{item.name}}</span>
</label>
</div>
Checkboxes are generated correctly but When source gets updated , checkbox doesn't update
/*js*/
$scope.disableCb = function () {
$scope.arrondissements[5].disable = true;
$scope.arrondissements[6].disable = true;
$scope.arrondissements[7].disable = true;
}
<!-- HTML -->
<button ng-click="disableCb()">disable</button>
Could you tell me why and how to fix it?
I made a Plunker : http://plnkr.co/edit/jD1l3NgJuduTOoskpeVM
You should define your $scope.disableCb function inside your controller function.
function controller( $scope) {
var vm = $scope;
$scope.title = 'controller';
$scope.arrondissements = JSON.parse('[{"name":"4e","checked":true,"disable":true},{"name":"5e","checked":false,"disable":false},{"name":"11e","checked":false,"disable":false},{"name":"12e","checked":false,"disable":false},{"name":"13e","checked":false,"disable":false},{"name":"14e","checked":false,"disable":false},{"name":"15e","checked":false,"disable":false},{"name":"16e","checked":false,"disable":false},{"name":"17e","checked":false,"disable":false},{"name":"18e","checked":false,"disable":false},{"name":"19e","checked":false,"disable":false},{"name":"20e","checked":false,"disable":false}]');
$scope.disableCb = function () {
$scope.arrondissements[5].disable = true;
$scope.arrondissements[6].disable = true;
$scope.arrondissements[7].disable = true;
}
}
I've also fixed how you used your directives. I've removed the value attribute on the checkboxes since they're redundant with ng-model.
I've fixed your usage of ng-disabled as well
<div ng-repeat="item in arrondissements" class="checkbox-inline ">
<label>
<input type="checkbox" ng-disabled="item.disable"
ng-model="item.checked" >
<span>{{item.name}}</span>
</label>
</div>
<button ng-click="disableCb()">disable</button>
see my fork on your plunker: http://plnkr.co/edit/v1fwlf7QH0189WAhv6qM?p=preview
I am very new to angular :). I would like to add a simple event one form element with a particular value, built by ng-repeat. This is how the HTML looks:
<div class="labels">
<div class="checkbox-element" ng-repeat="suggestName in $ctrl.suggests" ng-click="$ctrl.toggleSelection(suggestName, 'suggestsSelection', this)">
<label>
<input type="checkbox" name="suggestsSelection[]"
class="hidden"
value="{{suggestName}}"
><span></span>{{suggestName}}
</label>
</div>
<div class="optionary hidden">
<br>
<div class="question__text">Any other?</div>
<label><input type="text"
ng-model="$ctrl.survey.suggest_other"
name="suggests_other1"></label><br>
</div>
</div>
And the controller code:
vm.survey = {};
vm.suggests = ['quality', 'price', 'habbit', 'other'];
// selected
vm.survey.suggestsSelection = [];
// toggle selection for a given names
vm.toggleSelection = function toggleSelection(value, array, scope) {
var idx = vm.survey[array].indexOf(value);
// is currently selected
if (idx > -1) {
vm.survey[array].splice(idx, 1);
}
// is newly selected
else {
vm.survey[array].push(value);
}
};
What I need is to create an event that would toggle the class "hidden" from the div with class "optionary" after clicking on the last created checkbox ("other" in this case). Clicking on other checkboxes shouldn't affect the "optionary" div.
I tried with some configurations like:
if(scope.$last){
$(scope).closest('.optionary').toggleClass('hidden');
}
or similar. I don;t know what should be the way to approach the topic.
You need to use ng-show and a control variable. Take a look.
jsFiddle here: https://jsfiddle.net/U3pVM/24834/
<div ng-app class="labels" ng-controller="MyCtrl">
<div class="checkbox-element" ng-repeat="suggestName in suggests" ng-click="toggleSelection(suggestName, suggestsSelection, this)">
<label>
<input type="checkbox" ng-model="cbSuggest[$index]" name="suggestsSelection[]" class="hidden" value="{{suggestName}}">
<span>{{suggestName}}</span>
</label>
</div>
<div class="optionary hidden" ng-show="showOther">
<br>
<div class="question__text">Any other?</div>
<label><input type="text" ng-model="survey.suggest_other" name="suggests_other1"></label><br>
</div>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.survey = {};
$scope.suggests = ['quality', 'price', 'habbit', 'other'];
$scope.cbSuggest = [];
$scope.showOther = true;
// selected
$scope.survey.suggestsSelection = [];
// toggle selection for a given names
$scope.toggleSelection = function(value, array, scope) {
var showOther = true;
angular.forEach($scope.cbSuggest, function(k,v){
if(k) {
showOther = false;
}
});
$scope.showOther = showOther;
};
}
As you can see ng-repeat has special properties: https://docs.angularjs.org/api/ng/directive/ngRepeat
The one you're interested in is $last. You could add ng-change to your checkboxes, call a function with the paramter $last, and that function would set a scope variable. The hidden class could rely on that.
Something like this:
<input type="checkbox" name="suggestsSelection[]"
class="hidden"
ng-change="showHidden($last)"
value="{{suggestName}}">
And in your controller:
$scope.hidden = true;
$scope.showHidden = function(isLast) {
if (isLast) $scope.hidden = false;
else $scope.hidden = true;
}
And then you add ng-class to your div:
<div class="optionary" ng-class="{'hidden': hidden}">...</div>
How can I go about getting checked check box item's ID in a repeated list from a click of a button and add items to a variable / Array for later use?
html:
<input id="btnCheck" type="button" value="Next" ng-click="addSelected()" />
<div ng-controller="movieController">
<ul>
<li ng-repeat="movie in Movies">
<input id="chkBox-{{ movie.MovieID }}"
type="checkbox"
ng-checked="selection.indexOf(movie.MovieID) > -1"
ng-click="toggleSelection(movie.MovieID)"
/>
</li>
</ul>
</div>
Script:
$scope.AddSelected = function () {
var selected = $scope.selection
console.log(selected);
}
$scope.selection = [];
$scope.toggleSelection = function toggleSelection(movie) {
var idx = $scope.selection.indexOf(movie);
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
else {
$scope.selection.push(movie);
}
};
You could create a custom filter which would return a selected value id, for that you need pass two parameters to filter 1st parameter will perform check, if it is true then 2nd parameter property array will be return from the filter.
Markup
<body ng-app="app">
<div ng-controller="movieController">
{{(Movies | returnPropertyWhenCheckedTrue: 'checked' :'MovieID')}}
<ul>
<li ng-repeat="m in Movies">
<input id="chkBox-{{ m.MovieID }}" type="checkbox" ng-model="m.checked"/>
</li>
</ul>
</div>
</body>
Filter
app.filter('returnPropertyWhenCheckedTrue', function() {
return function(array, propertyToChecked, property) {
var returnArray = [];
angular.forEach(array, function(value, index) {
if (value[propertyToChecked])
returnArray.push(value[property]);
});
return returnArray;
}
});
Working Plunkr
You can use ng-options for multiple select. More usefull;
<select name="movies" ng-model="selectedMovieIDs"
ng-options="m.MovieID as m.MovieID for m in movies">
</select>
More more info : ngOptions
Please help, I have the following code
<div>
<input type="checkbox" id="chk1" ng-model="Status" />
<span ng-bind="Title"></span>
</div>
<div id="div1" ng-show="Status">
<span ng-bind="SpanTitle" ></span>
<input type="text" id="txtLastName"
ng-model="LastName"
ng-click="LastNameClick()"
ng-blur="LastNameOut()"
name="txtLastName" />
</div>
and when checkbox is being checked the div1 is shown but the input text cannot be clicked or written.
Any idea please?
Edit: Added controller from user's comment
function DController($scope) {
var defaultInputText = "hello";
$scope.Title = "check";
$scope.SpanTitle = "Span";
$scope.Status = false;
$scope.LastName = defaultInputText;
$scope.LastNameClick = function () {
if ($scope.LastName ==defaultInputText) {
$scope.LastName = "";
}
}
$scope.LastNameOut = function () {
if ($scope.LastName.length == 0) {
$scope.LastName = defaultInputText;
}
}
}
From code, that you have provided, I can suggest, that problem can be in css. May be some elements overlap the input.