How to call Json array value in other controller. Basically i work with nested controller. Nested controller will return first character of firstname and lastname.
For example if my first name is Anand Jee then It will return AJ, Rohan Kumar then it will return RK.
My AngularJS code.
//create module
var myApp = angular.module("myApp", []);
//create controller
myApp.controller("empCtrl", function ($scope) {
var Employees = [
{ FirstName: "Anand", LastName: "Jee", Roles: "Web Developer", Technology: ".NET" },
{ FirstName: "Pritus", LastName: "Dubey", Roles: "Window App Developer", Technology: "XAMARIN" },
{ FirstName: "Vineet", LastName: "Rai", Roles: "Web Developer", Technology: ".NET" },
{ FirstName: "Nilesh", LastName: "Pathak", Roles: "UI/UX Developer", Technology: "Photoshop" },
{ FirstName: "Vikesh", LastName: "Juyal", Roles: "Web Developer", Technology: "PHP" }
];
$scope.Employees = Employees;
});
myApp.controller("EmpShortName", function ($scope) {
$scope.getEmpShortName = function () {
//$scope.empShortName = $scope.Employees.FirstName + " " + $scope.Employees.LastName;//here is problem
$scope.empShortName = "NP";//For temp declaration
return $scope.empShortName;
};
});
PLUNKER DEMO
Pass the Employee object into the getEmpShortName function. Then just return the parsed value. Also, no need for the EmpShortName controller, just put the scope function in your empCtrl controller:
HTML:
<div class="empTextImage">{{getEmpShortName(emp)}}</div>
JS:
$scope.getEmpShortName = function (emp) {
return emp.FirstName.substr(0,1) + emp.LastName.substr(0,1);
};
Updated Plunker
Related
I am creating a CRUD webpage using angularjs and localstorage. The add, edit and delete functions all work perfectly well. I was able to use localstorage and save data after adding or deleting a user.
But i am unable to save edited user details on localstorage. They get erased on refresh of the webpage. The $scope.selectUser is the function I use to edit a user. Thanks in advance.
var myApp = angular.module("myApp", []);
myApp.controller("myController", function ($scope) {
console.log("in controller...");
$scope.newUser = {};
$scope.info = "";
if (localStorage.getItem("users") === null) {
$scope.users = [
{ email: "John#yahoo.com", firstName: "John", lastName: "Doe", contact: "281-283-2480", role: "Supplier-Admin", company: "Apple" },
{ email: "Rick#yahoo.com", firstName: "Rick", lastName: "Fraiser", contact: "987-283-2489", role: "Supplier-User", company: "Apple" },
{ email: "Sam#yahoo.com", firstName: "Sam", lastName: "Tarly", contact: "456-786-2480", role: "BuyerAdmin", company: "Samsung" }
];
localStorage.setItem("users", JSON.stringify($scope.users));
} else {
$scope.users = JSON.parse(localStorage.getItem("users"));
}
$scope.saveUser = function () {
console.log("Saving...");
$scope.users.push($scope.newUser);
$scope.info = "New User Added Successfully!";
$scope.newUser = {};
localStorage.setItem("users", JSON.stringify($scope.users));
//localStorage.setItem("email", $scope.users);
};
$scope.selectUser = function (user) {
$scope.clickedUser = user;
localStorage.setItem("users", JSON.stringify($scope.users));
};
$scope.deleteUser = function () {
console.log($scope.users.indexOf($scope.clickedUser));
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
localStorage.setItem("users", JSON.stringify($scope.users));
$scope.info = "User Deleted Successfully!";
};
$scope.clearInfo = function () {
$scope.info = "";
};
});
Here is my code
/// <reference path="angular.min.js" />
var myApp = angular.module("myModule", []).controller("myController", function($scope) {
var employees = [{
name: "Ben",
dateOfBirth: new Date("November 23,1980"),
gender: "Male",
salary: 55000.788
}, {
name: "Sara",
dateOfBirth: new Date("May 05,1970"),
gender: "Female",
salary: 68000
}, {
name: "Mark",
dateOfBirth: new Date("August 15,1974"),
gender: "Male",
salary: 57000
}, {
name: "Pam",
dateOfBirth: new Date("October 27,1979"),
gender: "Female",
salary: 53000
}, {
name: "Todd",
dateOfBirth: new Date("December 30,1983"),
gender: "Male",
salary: 60000
}];
$scope.employees = employees;
$scope.sortColumn = "name";
$scope.reverseSort = false;
$scope.sortData = function(column) {
$scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
$scope.sortColumn = column;
}
$scope.getSortClass = function(column) {
if ($scope.sortColumn == column)
return $scope.reverseSort ? 'arrow-down' : 'arrow-up';
return '';
}
});
I just want to ask that are employees,sortColumn and reverse sort are separate models or they belong to one model and what are the sortData and getSortClass in this files are they behavior in our model please explain...Thanks in advance.
SortData, contains the column name from which you want to sort and the reverseSort is a property of current employee object, which is set to true once the sort order is descending ( binary 0 ).
getSortClass fetch the current sort order in binary format ( 0 or 1) and update the reverseSort property accordingly.
Where to start... The variables in your codeblock all belong to the myController controller you have defined. They are instantiated when the controller is invoked through the $scope dependency, as well as any injected dependencies there may be.
sortData and getSortClass are functions declared in the scope of your controller. You cannot access them from another controller unless you traverse angulars $rootScope or using a listener. As for what those functions do, #kapil yadav has given an explanation.
<script>
<!-- A program to search for a friend from an object -->
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
}
alert(friends["steve"].lastName);
alert(friends.length);
var search = function(name)
{
document.write(name);
for (var nameSearch in friends)
{
alert(nameSearch.firstName);
if(friends[nameSearch].firstName===name)
{
return friends[nameSearch];
}
}
}
search("Wendy");
</script>
Theres a couple things wrong with your code:
Objects do not have a length property so the second alert for friends.length will not work
When you're using for in you are referencing the key of the object, so in this case it will be bill, steve, or wendy so when you do nameSearch.firstName it will be undefined since nameSearch is a string
Finally, the reason that your example is failing is because you're searching against case-sensitive text. wendy != Wendy. Also please keep in mind that triple equals checks the constructor.
To fix your code, you can try just lower-casing all of your search text:
var friends = {
bill: {
firstName: "Bill",
lastName: "Gates",
number: "205-555-1111",
address:["One Microsoft Day","Redmond","WA","90852"]
},
steve: {
firstName: "Steve",
lastName: "Jobs",
number: "408-555-2222",
address: ["One Infinite Loop", "Cupertino", "CA", "95014"]
},
wendy: {
firstName: "Wendy",
lastName: "Johnson",
number: "510-555-3333",
address: ["3555 Anyplace drive","New York", "NY","11001"]
}
};
var search = function(name) {
for (var nameSearch in friends) {
if(friends[nameSearch].firstName.toLowerCase()===name.toLowerCase()) {
return friends[nameSearch];
}
}
}
console.log(search("wendy"));
I am trying to inject uppercase filter as dependency injection to controller , I tried injecting the orderByFilter and it worked flawlessly.
you can refer to my sample Plunker project
PlunkerLink
var app = angular.module("myApp", [])
.controller('HomeController',function($scope,orderByFilter,uppercaseFilter)
{
$scope.sortOrder = '-id';
$scope.upperCase = 'fName';
$scope.users = [
{ id: 1, fName: 'Hege', lName: "Pege" },
{ id: 2, fName: 'Kim', lName: "Pim" },
{ id: 3, fName: 'Jack', lName: "Jones" },
{ id: 4, fName: 'John', lName: "Doe" },
{ id: 5, fName: 'Peter', lName: "Pan" }
];
$scope.users = orderByFilter($scope.users, $scope.sortOrder);
$scope.users = uppercaseFilter($scope.users, $scope.upperCase);
});
You will have to process array of object manually, as upperCase filter works on strings only. In your case it can be like this for example:
$scope.users = $scope.users.map(function(obj) {
obj[$scope.upperCase] = obj[$scope.upperCase].toUpperCase();
return obj;
});
Demo: http://plnkr.co/edit/QaCisLJAUI1eWbZNTtdz?p=preview
It might help you.
HTML code-sample
<span>{{ users.fName | limitTo : 3 | uppercase }}</span>
<span ng-bind="users.fName | limitTo : 3 | uppercase "></span>
AngularJs code-sample
<script>
angular.module("myApp").controller("myController"), function($filter){
var result = $filter(‘limitTo’)(users.fName, 3);
$filter(‘uppercase’)(result);
...
}
</script>
I'm sorry if this is an easy question. I'm new and probably don't understand the right things to search for to find the answer.
I've basically followed this angularJS tutorial http://www.youtube.com/watch?v=i9MHigUZKEM
I've gotten through all of it except setting up a factory that connects to my controller.
Here is the code for the factory:
demoApp.factory('simpleFactory', function(){
var people = [
{ name: 'Will', age: '30' },
{ name:'Jack', age:'26' },
{ name: 'Nadine', age: '21' },
{ name:'Zach', age:'28' }
];
var factory = {};
factory.getPeople = function() {
return people;
};
});
Here is the controller:
demoApp.controller('FirstCtrl', ['$scope', 'simpleFactory', function ($scope, simpleFactory) {
$scope.people = simpleFactory.getPeople();
}]);
And just a simple repeat in the HTML:
Name:
<input type="text" ng-model="filter.name"> {{ nameText }}
<ul>
<li ng-repeat="person in people | filter:filter.name | orderBy: 'name'">{{ person.name }}- {{ person.age }}</li>
</ul>
The error I get is "TypeError: Cannot call method 'getPeople' of undefined" in the javascript console.
Note: This all works correctly when within the controller I have the data object hardcoded in like so:
demoApp.controller('FirstCtrl', ['$scope', 'simpleFactory', function ($scope, simpleFactory) {
$scope.people = [
{ name: 'Will', age: '30' },
{ name:'Jack', age:'26' },
{ name: 'Nadine', age: '21' },
{ name:'Zach', age:'28' }
];
}]);
A small change in your service;
demoApp.factory('simpleFactory', function(){
var people = [
{ name: 'Will', age: '30' },
{ name:'Jack', age:'26' },
{ name: 'Nadine', age: '21' },
{ name:'Zach', age:'28' }
];
return {
getPeople: function() {
return people;
};
}
});
And in your controller
demoApp.controller('FirstCtrl', ['$scope', 'simpleFactory', function ($scope, simpleFactory) {
$scope.people = simpleFactory.getPeople();
}]);
Essentially you're just missing the return statement from your 'factory' object, but it might be clearer if you do a little renaming as well to avoid confusion.
Example, adapted from the AngularJS book:
demoApp.factory('People', function(){ // Renamed factory to be more descriptive
var people = {}; // Renamed 'factory' to 'people', as an object we can prototype more functions later
people.query = function() { // called query, but could be getPeople
return [ // just return a static array for now
{ name: 'Will', age: '30' },
{ name:'Jack', age:'26' },
{ name: 'Nadine', age: '21' },
{ name:'Zach', age:'28' }
];
}
return people;
});
So now your controller can pull this information in:
demoApp.controller('FirstCtrl', ['$scope', 'People', function ($scope, People) { // dependency injection
$scope.people = People.query();
});
So now we have a descriptive factory for People that returns an object, one of which is called query. We can later update this query function to read in parameters, fire off AJAX calls and do some complicated stuff. But one step at a time :)