How to access method in controller from another in angularjs - angularjs

How can i access a method in tableController from my menuController. Here is my code.i want to call addRow() method from select() in menu controller. these controllers are in different modules.Please Help me.
my menu controller
var menuApp = angular.module('menuApp', []);
menuApp.controller('menuController', ['tableService', function ($scope, tableService) {
$scope.menuItem = [
{
id: 1,
title: "new",
navigate:"N",
child: [{
id: 11,
title: "new11",
navigate: "N",
child: [{
id: 12,
title: "new12",
navigate: "Y",
url:"/Home/index"
}]
}]
},
{
id: 2,
title: "new",
child: [{
id: 21,
title: "new21",
child: [{
id: 22,
title: "new22"
}]
}]
}
];
$scope.select = function (data) {
if (data.navigate == "Y") {
alert(data.url);
tableService.add();
}
}
}]);
my table controller
tableApp.controller('tableController', function ($scope, $rootScope, $filter, $uibModal) {
$scope.filteredPeople = [];
$scope.currentPage = 1;
$scope.pageSize = 10;
$scope.people = [{ id: "1", name: "joe",disable:true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true }];
$scope.addRow = function () {
debugger;
$scope.people.unshift({
id: "",
name: "",
disable:false
});
$scope.getPage();
}
$scope.getPage = function () {
var begin = (($scope.currentPage - 1) * $scope.pageSize);
var end = begin + $scope.pageSize;
$scope.filteredPeople = $filter('filter')($scope.people, {
id: $scope.idFilter,
name: $scope.nameFilter
});
$scope.totalItems = $scope.filteredPeople.length;
$scope.filteredPeople = $scope.filteredPeople.slice(begin, end);
};
$scope.getPage();
$scope.pageChanged = function () {
$scope.getPage();
};
$scope.open = function () {
$scope.id = generateUUID();
};
$scope.dblclick = function (index) {
for (var i = 0; i < $scope.filteredPeople.length; i++) {
$scope.filteredPeople[i].disable = true;
}
return index.disable = false;
}
$scope.rowSelect = function (rowdata) {
alert(rowdata.name);
}
$scope.openInput = function (index) {
debugger;
var modalInstance = $uibModal.open({
templateUrl: '/Home/index',
controller: 'testController',
resolve: {
items: function () {
return index;
},
cat: function () {
return 'Account';
}
}
});
}
});

Example of a service shared between controllers & directives
/**
* store and share data between controllers & directives
*/
angular.module('interfaceApp').service('shareData', function () {
this.datas = [];
this.add = function (data) {
this.datas.push(data);
};
//retourne l'élément correspondant à la clé ( utilise la date comme clé )
this.getElement = function (key) {
......
return ;
};
this.getDatas = function () {
return this.datas;
};
});
/* Controller */
var searchModule = angular.module('searchModule', []);
// inject the service in the controller
.controller('searchCtrl', function ($scope, shareData ) {
shareData.add( ... );
console.log( shareData.getDatas() );
});
A service is a singleton, so all controllers using it acces to the same datas ( when they call shareData.getDatas() )

Related

why add newRecord[] is empty

I have a problem when adding a newRecord, the console always outputs [].
Please help me.
_storePR2.add(_key.data);
_storePR2.commitChanges();
var newRecord = _storePR2.getNewRecords();
console.log('newRecord',newRecord);
Output: newRecord []
enter image description here
this my store code and model :
Ext.define('Sasmita.store.vending.purchase.Purchasegoodrec', {
extend: 'Ext.data.Store',
requires: [
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json',
'Ext.data.Field'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
storeId: 'vending.purchase.Purchasegoodrec',
proxy: {
type: 'ajax',
url: 'jsonresult/Sasmita_Vending_Purchase/getPurchaseGoodrec',
reader: {
type: 'json',
root: 'data',
idProperty: 'sitecode2'
}
},
fields: [
{
name: 'purchase_id_tr'
},
{
name: 'parent_id'
},
{
name: 'file_ext'
},
{
name: 'file_name'
},
{
name: 'file_size'
},
{
name: 'description'
},
{
name: 'id'
},
{
name: 'id_file'
},
{
name: 'id_po'
},
{
name: 'qty_hasil'
},
{
name: 'no_pr'
},
{
dateFormat: 'Ymd',
name: 'date_pr',
type: 'date'
},
{
name: 'warehouse'
},
{
name: 'warehouse_name'
},
{
name: 'row_created_by'
},
{
name: 'row_created_datetime'
},
{
name: 'row_changed_by'
},
{
name: 'row_changed_datetime'
},
{
name: 'title'
},
{
name: 'notes'
},
{
name: 'qty_order'
},
{
name: 'no_po'
},
{
name: 'date_po'
},
{
name: 'supplier'
},
{
name: 'package'
},
{
name: 'qty_approve'
},
{
name: 'purchase_product_name'
},
{
name: 'unit'
},
{
name: 'unit_price'
},
{
name: 'total_price'
},
{
name: 'total_price_head'
},
{
name: 'vat'
},
{
name: 'net_price'
},
{
name: 'sum_total'
}
]
}, cfg)]);
}
});
and this my controller action button choose :
var me = this;
var _panel = me.getMainPanel();
var _tabpanel = _panel.down('#tabmaintain');
var _activetab = _tabpanel.getActiveTab();
var _window = button.up('window');
var _grid = _window.down('grid');
//var _girdd = this.getPanelSearch();
//var _grids = _girdd.down('grid');
var _gridSelected = _grid.getSelectionModel().getSelection();
//var row = _grid.store.indexOf(_gridSelected);
//console.log(row);
console.log(_gridSelected);
console.log(_grid);
//console.log(_girdd.down('grid'));
//selected=[];
//Check selected product
if(_gridSelected.length===0){
Ext.Msg.alert('Warning','Please select product');
return;
}
//Submit Product
var _gridPR = _activetab.down('#detailProduct');
var _storePR2 = _gridPR.getStore();
//console.log(_storePR2.data);
Ext.Array.each(_gridSelected,function(_key,_value,item){
//console.log(selected.push(item));
_validate = true;
_storePR2.each(function(_storeData,_storeIndex){
console.log(_key.data);
if(_storeData.data.no_po === _key.data.no_po){
_validate = false;
Ext.Msg.alert('Warning','The Product had been picked');
return;
}
});
if(_validate){
// Add record to the store by data
_storePR2.add(_key.data);
// Get array of new records from the store
var newRecords = _storePR2.getNewRecords();
console.log('newRecord',newRecords);
// Commit changes after getting new records
_storePR2.commitChanges();
_window.close();
}
});
That is because you committed the changes, so there are no longer any 'new records'.
Try to get the new records before committing the changes:
// Add record to the store by data
_storePR2.add(_key.data);
// Get array of new records from the store
var newRecords = _storePR2.getNewRecords();
console.log('newRecord',newRecords);
// Commit changes after getting new records
_storePR2.commitChanges();
Here is a fiddle.
First you need to add records to store and commit changes,then get new records.
grid_store.add({'Name':"ab",'dob':"099"})
grid_store.commitChanges();
var newRecord = grid_store.getNewRecords()
console.log('newRecord',newRecord);
});
Here is a fiddle: http://jsfiddle.net/2p78md5t/3/

I want to insert the data into an array but it shows a warning message that duplicates are not allowed

$scope.data = {
"items": [{
id: 1,
name: "Vijay",
email: "vijay#gmail.com",
mobile: "9090909090",
salary: 98690
}, {
id: 2,
name: "ajay",
email: "ajay#gmail.com",
mobile: "9190909090",
salary: 98969
}, {
id: 3,
name: "mahesh",
email: "mahesh#gmail.com",
mobile: "8090909090",
salary: 78555
}, {
id: 4,
name: "ganesh",
email: "ganesh#gmail.com",
mobile: "9099909090",
salary: 48756
}, {
id: 5,
name: "balu",
email: "balu#gmail.com",
mobile: "9880909090",
salary: 98909
}, {
id: 6,
name: "kapil",
email: "kapil#gmail.com",
mobile: "9090907790",
salary: 76595
}]
}
$scope.items = $scope.data.items;
$scope.addItem = function(item) {
$scope.items.filter(function(el) {
if (el.id !== item.id) {
console.log(el.id, "xxxxxxxxxxxx inside if xxxxxxxxxxx", item.id);
$scope.items.push(item);
// console.log($scope.items,item);
$scope.item = {};
} else {
console.log("sdhjkkkkk inside else kkkkkkkkkkkkkkk")
alert("already exist");
}
});
It's because you trying to push element on each iteration of 'filter' loop if id of your item !== item id of array element.
Also, filter is not what you need for this. It returns new array.
You can use 'every' for this. For example:
$scope.addItem = function(item) {
if (checkEquality(item, $scope.items)) {
$scope.items.push(item);
}
};
function checkEquality(element, array) {
return array.every(function(item) {
return item.id !== element.id;
});
}

Capturing checkbox values to table

I'm trying to create a form that will capture input, select and checkbox values and post them to a table. Everything seems to be working fine, with the exception of the checkboxes. What am I doing wrong?
https://jsfiddle.net/mujaji/uvkzmyox/8/
var app = angular.module("myapp", []);
app.controller("ListController", ['$scope', function($scope) {
$scope.jobtypes = ['accountant', 'janitor', 'ceo', 'receptionist'];
$scope.hobbies = [{name: "long walks on the beach", id: "1", isChecked: false},{name: "eating cheese", id: "2", isChecked: false},{name: "writing haikus", id: "3", isChecked: false},{name: "looking for bigfoot", id: "4", isChecked: false},{name: "watching police academy", id: "5", isChecked: false}];
$scope.personalDetails = [
{
'fname':'Muhammed',
'lname':'Shanid',
'jobtype': 'ceo',
'email':'shanid#shanid.com',
'active': true,
'hobbies': [{name: "long walks on the beach", id: "1"},{name: "watching police academy", id: "5"}]
},
{
'fname':'John',
'lname':'Abraham',
'jobtype': 'accountant',
'email':'john#john.com',
'active': true,
'hobbies': [{name: "writing haikus", id: "3"},{name: "looking for bigfoot", id: "4"}]
},
{
'fname':'Roy',
'lname':'Mathew',
'jobtype': 'janitor',
'email':'roy#roy.com',
'active': false,
'hobbies': [{name: "eating cheese", id: "2"}]
}];
$scope.addNew = function(personalDetails){
$scope.personalDetails.push({
'fname': personalDetails.fname,
'lname': personalDetails.lname,
'email': personalDetails.email,
'jobtype': personalDetails.jobtype,
});
$scope.PD = {};
};
$scope.remove = function(){
var newDataList=[];
$scope.selectedAll = false;
angular.forEach($scope.personalDetails, function(selected){
if(!selected.selected){
newDataList.push(selected);
}
});
$scope.personalDetails = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.personalDetails, function (personalDetails) {
personalDetails.selected = $scope.selectedAll;
});
};
}]);
The problem your facing is caused by the fact that hobbies and their checked state is outside the scope of your addNew(personalDetails) function.
Although not ideal for angular, something like this would work:
$scope.addNew = function(personalDetails) {
//get all checked hobbies
let selectedHobbies = [];
$scope.hobbies.forEach(function(hobby) {
if (hobby.isChecked) selectedHobbies.push(hobby);
});
$scope.personalDetails.push({
'fname': personalDetails.fname,
'lname': personalDetails.lname,
'email': personalDetails.email,
'jobtype': personalDetails.jobtype,
'hobbies': selectedHobbies
});
$scope.PD = {};
};
EDIT
The answer above is really a pure javascript approach to filtering by selected hobbies. A more 'angular' approach would be to break your filter logic out into its own function so that you're not mixing concerns. For example:
Add the 'filterFilter' dependency to your controller:
app.controller("ListController", ['$scope','filterFilter',
function($scope, filterFilter) { ... }
then in your controller, define an array to hold your selected hobbies and add a filter helper to filter by isChecked:
$scope.hobbiesSelection = [];
$scope.selectedHobbies = function selectedHobbies() {
return filterFilter($scope.hobbies, { selected: true });
};
place a watch on the hobbies object to watch for changes to selected hobbies:
$scope.$watch('hobbies|filter:{isChecked: true}', function (hobbies) {
$scope.hobbiesSelection = hobbies;
}, true);
and finally, you can update your addNew() method to simply be:
$scope.addNew = function(personalDetails){
$scope.personalDetails.push({
'fname': personalDetails.fname,
'lname': personalDetails.lname,
'email': personalDetails.email,
'jobtype': personalDetails.jobtype,
'hobbies': $scope.selectedHobbies
});
$scope.PD = {};
};
So while there is a bit more code (and complexity) there for this example, you are separating the logic from the data a bit better. There is working example here: https://jsfiddle.net/mt0tvkwm/

Angular 2 loop through a list with some delay

How do I loop through an array with some delay with Angular 2 and TypeScript?
I have an array,
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
I want to loop through the list and display the names with a 2000ms delay.
<div *ngFor="let student of students">
{{student.name}}
</div>
doesn't work with a delay but is looping all at once.
Just use setTimeout. For example (* not tested):
students: Array<any> = [ ];
populateArrayWithDelay():void{
let people = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
for(let i = 0; i < people.length; i++){
let student = people[i];
setTimeout(() => {
this.students.push(student);
}, 2000*(i+1));
}
}
Plunker example
export class App {
name:string;
students: Array<any> = [
{
name: "Alan"
},
{
name: "Jake"
},
{
name: "Harry"
},
{
name: "Susan"
},
{
name: "Sarah"
},
{
name: "Esther"
}
];
constructor() {
var timer = 0;
this.$students = Observable.from([[], ...this.students])
.mergeMap(x => Observable.timer(timer++ * 1000).map(y => x))
.scan((acc, curr) => {acc.push(curr); return acc;});
}
}

geting json inventory id using resource

i cant get and ID from my json api, how can i do that? I am doing like $scope.info.id in my delete function but id doesnt work like that.
Here is my delete function
app.controller('InventoryCtrl', function($scope, $http, Inventory, $location) {
//getting the objects from Inventory
$scope.info = Inventory.query();
$scope.deleteInv = function () {
Inventory.drop({id: $scope.info.id}, function() {
$location.path('/');
});
};
});
here is my factory
app.factory('Inventory', function($resource, $http) {
return $resource('http://localhost/api/v1/inventory/:id', {id: "#id"},
{
drop: {
method: 'DELETE',
params: {id: "#id"}
}
}
);
});
And here is my api
{
meta: {
limit: 20,
next: null,
offset: 0,
previous: null,
total_count: 3
},
objects: [
{
category: {},
count: 1,
created: "2014-02-28T11:54:02.831409",
description: "dasdasdasdsa",
id: 20,
location: "asd",
name: "adas11",
resource_uri: "/api/v1/inventory/20",
status: "sad"
},
{
category: {},
count: 1,
created: "2014-02-28T11:54:03.708003",
description: "dasdasdasdsa",
id: 21,
location: "asd",
name: "adas11",
resource_uri: "/api/v1/inventory/21",
status: "sad"
},
]
}
I don't think you should call "drop" function. Instead you should call the 'delete' function which you specified in your factory.
$scope.deleteInv = function () {
Inventory.delete({id: $scope.info.id}, function() {
$location.path('/');
});

Resources