I am trying to sync div with textbox.
For example, I created 2 nodes i.e Node 1 and Node 2 and when I select node1 and I enter title and location then title and location should sync with Node1 so when I enter title while I have selected node1 then title value should get reflected for node1 and after entering title and location next time when I select node1 then title and location value should be reflected in my textbox.
I created this below Fiddle to demonstrate the problem : http://jsfiddle.net/quk6wtLx/2/
$scope.add = function (data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
data.nodes.push({ name: newName, nodes: [],selected : false });
};
$scope.tree = [{ name: "Node", nodes: [], selected: false }];
$scope.setActive = function (data) {
clearDivSelection($scope.tree);
console.log(data);
data.selected = true;
};
I am not getting how to do this.
You need to bind the form elements with the data you are appending to the tree.
Check this snippet
var app = angular.module("myApp", []);
app.controller("TreeController", function ($scope) {
$scope.delete = function (data) {
data.nodes = [];
};
$scope.add = function (data) {
var post = data.nodes.length + 1;
var newName = data.name + '-' + post;
data.nodes.push({ name: newName, nodes: [],selected : false, myObj: { name: newName} });
};
$scope.tree = [{ name: "Node", nodes: [], selected: false }];
$scope.setActive = function ($event, data) {
$event.stopPropagation();
$scope.selectedData = data;
clearDivSelection($scope.tree);
data.selected = true;
};
function clearDivSelection(items) {
items.forEach(function (item) {
item.selected = false;
if (item.nodes) {
clearDivSelection(item.nodes);
}
});
}
});
ul {
list-style: circle;
}
li {
margin-left: 20px;
}
.active { background-color: #ccffcc;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<ul ng-app="myApp" ng-controller="TreeController">
<li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>
<script type="text/ng-template" id="tree_item_renderer.html">
<div ng-class="{'active': data.selected}" > {{data.myObj.name}}</div>
<button ng-click="add(data)">Add node</button>
<button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>
<ul>
<li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'" ng-click="setActive($event, data)"></li>
</ul>
</script>
<div style="margin-left:100px;">
Title : <input type="text" ng-model="selectedData.myObj.name" />
Location : <input type="text" ng-model="selectedData.myObj.location" />
</div>
</ul>
You can check the binding documentation for AngularJs and all the possibilities https://docs.angularjs.org/guide/databinding
Related
HTML :-
<div class="row" style="margin-left: 10px;" data-bind="foreach: {data: data, as: 'data1'}">
<span style="color: red; display: none;" data-bind="attr:{'id':data1.mandatory!=0?'id'+data1.dynamicid:''},text: 'You have selected ' +app.vm.observables.totalSelected()+ ' Observation areas. Please restrict to only 2.'"></span>
</div>
here the observable is same for every div element id so value is showing same how to do it dynamically?
JAVASCRIPT :-
`$('#id'+dynamicid+' input:checkbox.paramValues:checked').each(function(e){
DataImprove++;
});`
if(DataImprove>2){
vm.observables.totalSelected(DataImprove);
}
Need to create observables dynamically based on the div element ids and show it in the frontend HTML.
I'm not entirely sure I understand what you are trying to do, but hopefully this helps
I think it would make sense to move some of the functionality out out the view and into a viewModel
var externalData = [{
mandatory: false,
dynamicid: 1,
}, {
mandatory: false,
dynamicid: 2,
}, {
mandatory: 1,
dynamicid: 3,
}, {
mandatory: false,
dynamicid: 4,
}];
function ViewModel() {
var self = this;
self.data = ko.observableArray([]);
self.totalSelected = ko.pureComputed(function() {
return self.data().filter(function(i) {
return i.selected() === true;
}).length;
});
self.selectedText = ko.pureComputed(function(){
return 'You have selected ' + self.totalSelected() + ' Observation areas.';
});
var mappedData = externalData.map(function(item) {
return {
mandatory: item.mandatory,
dynamicid: item.dynamicid,
selected: ko.observable(false),
mandatoryStatus: item.mandatory == true ? 'mandatory' : ''
};
});
self.data(mappedData);
}
var vm = new ViewModel();
ko.applyBindings(vm);
.mandatory {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: selectedText"></span>
<ul data-bind="foreach: {data: data, as: 'data1'}">
<li data-bind="class: mandatoryStatus">
<label data-bind="text: dynamicid"></label>
<input type="checkbox" data-bind="checked: selected" />
</li>
</ul>
Sorry for my English. I am trying to pre select those checkboxes whos values have been saved in the database. I did it using javascript in vuejs but those selected checkboxes values are not storing in array.
My code is like
role.component.js
getRoleRowData(data) {
this.roleaction = "edit";
this.addrolemodal = true;
console.log(data.role_id);
axios
.post(apiUrl.api_url + "getRolePermissionData", {
role_id: data.role_id
}).then(
result => {
this.permid = result.data;
var list = [];
result.data.forEach(function(value) {
list.push(value.perm_id);
});
var options = list;
for (var i = 0; i < options.length; i++) {
if (options[i]) document.querySelectorAll('input[value="' + options[i] + '"][type="checkbox"]')[0].checked = true;
}
},
error => {
console.error(error);
}
);
this.addrole = data;
},
And role.component.html
<div class="col-md-8">
<b-form-fieldset>
<div class="form" id="demo">
<h6>Permissions</h6>
<span v-for="perm_name_obj in listPermissionData">
<input type="checkbox" class="perm_id" v-bind:value="perm_name_obj.perm_id" name="perm_id" id="perm_name" v-model="checkedPerm_Id"> {{perm_name_obj.perm_name}}<br>
</span>
<span>Checked names: {{ checkedPerm_Id }}</span>
</div>
</b-form-fieldset>
</div>
And the Output
And the Ouput I got
In simple words I want to pre check checkboxes in vuejs of which values are stored in database.
See the following example, using simulation data
var app = new Vue({
el: '#app',
data () {
return {
listPermissionData: [],
checkedPerm_Id: []
}
},
created () {
setTimeout(_=>{
//Here simulates axois to request Permission data
this.listPermissionData = [
{perm_id:1,perm_name:'perm_name1'},
{perm_id:2,perm_name:'perm_name2'},
{perm_id:3,perm_name:'perm_name3'},
{perm_id:4,perm_name:'perm_name4'},
{perm_id:5,perm_name:'perm_name5'}
];
//Here simulates axois to request Selected Permissions (result.data)
var selected = [
{perm_id:2,perm_name:'perm_name2'},
{perm_id:5,perm_name:'perm_name5'}
]
this.checkedPerm_Id = selected.map(o=>o.perm_id)
},1000)
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div class="form">
<h6>Permissions</h6>
<span v-for="perm_name_obj in listPermissionData">
<input type="checkbox" class="perm_id" v-bind:value="perm_name_obj.perm_id" name="perm_id" id="perm_name" v-model="checkedPerm_Id"> {{perm_name_obj.perm_name}}<br>
</span>
<span>Checked names: {{ checkedPerm_Id }}</span>
</div>
</div>
I solved my problem, here is my code
role.component.js
getRoleRowData(data) {
this.roleaction = "edit";
this.addrolemodal = true;
console.log(data.role_id);
let tempthis = this;
axios
.post(apiUrl.api_url + "getRolePermissionData", {
role_id: data.role_id
}).then(
result => {
this.permid = result.data;
var list = [];
result.data.forEach(function(value) {
//by using tempthis variable we provided the current access to the checkedPerm_Id array which not accessible from out of the function which is getRoleRowData
tempthis.checkedPerm_Id.push(value.perm_id);
list.push(value.perm_id);
});
},
error => {
console.error(error);
}
);
this.addrole = data;
},
I want to filter object inside nested ng-repeat.
HTML:
<div ng-controller="MyController">
<input type="text" ng-model="selectedCityId" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
Controller:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (location.city_id === parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.item = function (detail) {
if ($scope.selectedCityId === undefined || $scope.selectedCityId.length === 0) {
return true;
}
if (detail.pin == parseInt($scope.selectedCityId)) {
return true;
}
};
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Here's the fiddle:
http://jsfiddle.net/suCWn/210/
I want to use multiple filter inside ng-repeat.
Example: Whenever user enters the ID in the input box. The list should filter based on cityID or PinCode.
if user enter '129818' it should show pin code result of 129818 along with its parent cityID
Similarly, if a user enter 400, the list should filter and show cityID result with 400 along with its child pin code.
EDIT:
Update Code http://codepen.io/chiragshah_mb/pen/aZorMe?editors=1010]
First, you must not filter locations with matching details. Use something like this in the search filter:
$scope.search = function (location) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || location.city_id === id ||
location.details.some(function(d) { return d.pin === id });
};
To show details if filtered by cityID, you have to find the parent location and check if it was filtered.
$scope.item = function (detail) {
var id = parseInt($scope.selectedCityId);
return isNaN(id) || detail.pin === id || locationMatches(detail, id);
};
function locationMatches(detail, id) {
var location = locationByDetail(detail);
return location && location.city_id === id;
}
function locationByDetail(detail) {
var shops = $scope.shops;
for(var iS = 0, eS = shops.length; iS != eS; iS++) {
for(var iL = 0, eL = shops[iS].locations.length; iL != eL; iL++) {
if (shops[iS].locations[iL].details.indexOf(detail) >= 0) {
return shops[iS].locations[iL];
}
}
}
}
EDIT Another, more flexible solution would be to remove all the filters from ngRepeats and do the filtering in a method that you call on ngChange of the search text. Here is the basic structure for this approach.
myApp.controller('MyController', function($scope, $http) {
var defaultMenu = [];
$scope.currentMenu = [];
$scope.searchText = '';
$http.get(/*...*/).then(function (menu) { defaultMenu = menu; } );
$scope.onSearch = function() {
if (!$scope.searchText) {
$scope.currentMenu = defaultMenu ;
}
else {
// do your special filter logic here...
}
};
});
And the template:
<input type="text" ng-model="searchText" ng-change="onSearch()" />
<ul>
<li ng-repeat="category in currentMenu">
...
</li>
</ul>
I have updated your filters. The problem is in your search filter you are only checking for the city_id, what you should do is:
Check if the typed id is city_id
Check if typed id is a pid of a child detail of given location
Similar thing for the item filter:
Check if the typed id is a pid of the detail being filtered
Check if the typed id is a city_id of the parent location of the detail passed in
Here is a working jsFiddle. I hope this helps.
By simply modifying the JSON to include the city_id for children so you don't need to loop through it to get the parent's city_id, the solution is as easy as this:
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.search = function (location) {
if (!$scope.selectedCityId)
return true;
//if user's input is contained within a city's id
if (location.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
for (var i = 0; i < location.details.length; i++)
//if user's input is contained within a city's pin
if (location.details[i].pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
$scope.item = function (detail) {
if (!$scope.selectedCityId)
return true;
//if user's input is contained within a city's id
if (detail.city_id.toString().indexOf($scope.selectedCityId) > -1)
return true;
//if user's input is contained within a city's pin
if (detail.pin.toString().indexOf($scope.selectedCityId) > -1)
return true;
};
Modified JSON
$scope.shops=[{"category_id":2,"locations":[{"city_id":368,"details":[{"city_id":368,"pin":627718,"state":'MH'}]}]},{"name":"xxx","category_id":1,"locations":[{"city_id":400,"region_id":4,"details":[{"city_id":400,"pin":627009,"state":'MH'},{"city_id":400,"pin":129818,"state":'QA'}]},]},];});
If directly modifying the JSON is not possible, you can modify it like this in this controller directly after this $scope.shops = ...json... statement:
for(var i=0; i<$scope.shops.length; i++)
for(var j=0, cat=$scope.shops[i]; j<cat.locations.length; j++)
for(var k=0, loc=cat.locations[j]; k<loc.details.length; k++)
loc.details[k].city_id=loc.city_id;
Working fiddle:
http://jsfiddle.net/87e314a0/
I tried to make the solution easier to understand :
index.html :
<div ng-controller="MyController">
<input type="text" ng-model="search.city_id" />
<ul>
<li ng-repeat="shop in shops">
<p ng-repeat = "locations in shop.locations | filter:search.city_id" style="display: block">
City id: {{ locations.city_id }}
<span style="padding-left: 20px; display: block;" ng-repeat="detail in locations.details | filter:item">Pin code: {{detail.pin}}</span>
</p>
</li>
</ul>
</div>
app.js :
var myApp = angular.module('myApp', []);
myApp.controller('MyController', function ($scope) {
$scope.shops =
[
{
"category_id":2,
"locations":[
{
"city_id":368,
"details": [{
"pin": 627718,
"state": 'MH'
}]
}
]
},
{
"name":"xxx",
"category_id":1,
"locations":[
{
"city_id":400,
"region_id":4,
"details": [{
"pin": 627009,
"state": 'MH'
},{
"pin": 129818,
"state": 'QA'
}]
},
]
},
];
});
Here's the fiddle :
mySolution
See the plnkr http://plnkr.co/edit/atoDX2TqZT654dEicqeS?p=preview
How to move item from the list to the another empty list. Currently an item can't be moved once the destination list gone empty... How I can fix this for my application?
Here is the code sniped on tags for my application:
<div class="row">
<div class="span4 offset2" style="overflow-y:auto; height:150px;">
<ul ui-sortable="sortableOptions" ng-model="allDiagnosisFromDb" id="sourceList" ng-class="{'minimalList':sourceEmpty()}" class="connector">
<li class="alert alert-danger nomargin" ng-repeat="item in allDiagnosisFromDb">{{item.Name}}</li>
</ul>
</div>
<div class="span4" style="overflow-y:auto; height:150px; background-color:lightgray">
<ul ui-sortable="sortableOptions" id="targetList" ng-model="model" ng-class="{'minimalList':sourceEmpty()}" class="connector">
<li class="alert alert-info nomargin" ng-repeat="item in model">{{item.Name}}</li>
</ul>
</div>
</div>
code on angularjs controller:
function loadAllDiagnosis() {
$scope.allDiagnosisFromDb = [];
diagnosisPreferanceService.getAllDiagnosis()
.success(function (data) {
$scope.allDiagnosisFromDb = data;
})
.error(function (xhr) {
alert('error');
});
}
// init
$scope.model = [
{
"Id": 23,
"Name": "First tem."
}
];
$scope.sortableOptions = {
connectWith: '.connector'
}
// watch, use 'true' to also receive updates when values
// change, instead of just the reference
$scope.$watch("model", function (Name) {
console.log("Model: " + Name.map(function (e) { return e.Id }).join(','));
}, true);
// watch, use 'true' to also receive updates when values
// change, instead of just the reference
$scope.$watch("allDiagnosisFromDb", function (Name) {
console.log("allDiagnosisFromDb: " + Name.map(function (e) { return e.Id }).join(','));
}, true);
$scope.sourceEmpty = function () {
return $scope.allDiagnosisFromDb.length == 0;
}
$scope.modelEmpty = function () {
return $scope.model.length == 0;
}
Thanks in advance,,,,,,,,,:)
You can refer the below link exactly how you want it to be.
http://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/simple
angular.module("demo").controller("SimpleDemoController", function($scope) {
$scope.models = {
selected: null,
lists: {"A": [], "B": []}
};
// Generate initial model
for (var i = 1; i <= 3; ++i) {
$scope.models.lists.A.push({label: "Item A" + i});
$scope.models.lists.B.push({label: "Item B" + i});
}
// Model to JSON for demo purpose
$scope.$watch('models', function(model) {
$scope.modelAsJson = angular.toJson(model, true);
}, true);
});
I am trying to add objects to $scope.orderitems and if the object is already in the $scope.orderitems I want to change the quantity property of the object using angular.forEach instead of adding another object. Whenever I call the additem function I get an error that orderitems is not defined.
Here is my code
HTML
<input type="text" ng-model="item.name">
<button type="button" ng-click="additem(item)">
<ul>
<li ng-repeat="orderitem in orderitems">
<p>{{ orderitem.name }} | {{ orderitem.qty }}</p>
</li>
</ul>
JS
app.controller('OrderCtrl', function($scope) {
$scope.orderitems = [];
$scope.additem = function(data) {
angular.forEach(orderitems, function(orderitem) {
if (orderitem.id === data.id) {
orderitem.qty = orderitem.qty++;
} else {
data.qty = 1;
$scope.orderitems.push(data);
}
});
};
});
Here's a working fiddle: http://jsfiddle.net/rodhartzell/hbN4G/
HTML
<body ng-app="app">
<div ng-controller="OrderCtrl">
<input type="text" ng-model="item.name">
<button type="button" ng-click="additem()">add</button>
<ul>
<li ng-repeat="orderitem in orderitems">
<p>{{ orderitem.name }} | {{ orderitem.qty }}</p>
</li>
</ul>
</div>
CONTROLLER
var app = angular.module('app', []);
app.controller('OrderCtrl', function($scope) {
$scope.orderitems = [{name: 'foo', id:1, qty:1}];
$scope.additem = function() {
var exists = false;
var data = {
id : $scope.orderitems.length + 1,
name: $scope.item.name,
qty: 1
}
angular.forEach($scope.orderitems, function (item) {
if (item.name == data.name) {
exists = true;
item.qty++;
return false;
}
});
if(!exists){
$scope.orderitems.push(data);
}
};
});
$scope.orderitems = [];
$scope.additem = function(data) {
var item = null
angular.forEach(orderitems, function(orderItem) {
if (orderItem.id === data.id) {
item = orderItem
return false;
}
});
if (item == null) {
item = {
id: data.id, qty : 0
}
$scope.orderitems.push(item)
}
item.qty++
};