I am new to angularjs.I am building a very simple web application.The code structure is given below.I have a simple view showing candidate list and seraching candidate from data base.
My Javascript controller:
appRoot.controller('CandidateController', function ($scope, $location, $resource) {
var searchcandidates={
Name:$("#txtname").val(),
Email:$("#txtemail").val()
};
var Listcandidates = $resource('/api/Candidate', {Name:$("#txtname").val(), Email:$("#txtemail").val()}, { update: { method: 'GET' } });
$scope.candidateslist = [];
Listcandidates.query(function (data) {
$scope.candidateslist.length = 0;
angular.forEach(data, function (CandidateData) {
$scope.candidateslist.push(CandidateData);
})
});
$scope.SearchCandidates = function () {
alert($("#txtname").val());
var list = $resource('/api/Candidate', { id: "2" } );
}
var init = function () {
}
init();
});
My Cshtml:
#{
Layout = null;
}
<div class="FormHeader"><span class="searCandidate"></span>Search Result</div>
<div class="blank"></div>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<!--Sidebar content-->
Search:
<label>Name</label>
<input type="text" id="txtname" name="name" />
<label>Email</label>
<input type="text" id="txtemail" name="email" />
<input type="button" value="Save" ng-click="SearchCandidates()" />
</div>
<div class="span10">
<!--Body content-->
<ul class="candidates">
<li ng-repeat="candidate in candidateslist"
class="thumbnail phone-listing">
#*<img ng-src="{{phone.imageUrl}}">
{{phone.name}}*#
<div class="item">
<span class="green leftMrg">{{candidate.name}}</span>
<span class="leftMrg">{{candidate.skill}}</span>
<span class="grey leftMrg">Resume ID: {{candidate.id}}</span>
<div class="blank"></div>
<div class="blank"></div>
</div>
<div class="item">
<span class="bold">{{candidate.exporganization}} </span>
<span>Education:{{candidate.eduname}}</span>
<span>{{candidate.totalexperience}}</span>
<span>Preferred Location: {{candidate.location}}</span>
</div>
<p></p>
</li>
</ul>
</div>
</div>
</div>
My app.js:
var appRoot = angular.module('main', ['ngRoute', 'ngGrid', 'ngResource', 'angularStart.directives', 'kendo.directives']); //Define the main module
appRoot
.config(['$routeProvider', function ($routeProvider) {
//Setup routes to load partial templates from server. TemplateUrl is the location for the server view (Razor .cshtml view)
$routeProvider
.when('/home', { templateUrl: '/home/main', controller: 'MainController' })
.when('/contact', { templateUrl: '/home/contact', controller: 'ContactController' })
.when('/about', { templateUrl: '/home/about', controller: 'AboutController' })
.when('/demo', { templateUrl: '/home/demo', controller: 'DemoController' })
.when('/candidate', { templateUrl: '/home/candidate', controller: 'CandidateController' })
.otherwise({ redirectTo: '/home' });
}])
.controller('RootController', ['$scope', '$route', '$routeParams', '$location', function ($scope, $route, $routeParams, $location) {
$scope.$on('$routeChangeSuccess', function (e, current, previous) {
$scope.activeViewPath = $location.path();
});
}]);
My CandidateController.cs
public class CandidateController : ApiController
{
CandidateSearchDAL objCandidateSearchDAL = new CandidateSearchDAL();
// GET api/<controller>
public IEnumerable<CandidateModel> Get()
{
List<CandidateModel> lstCandidates = objCandidateSearchDAL.GetSearchCandidates();
return lstCandidates;
}
// GET api/<controller>/5
public string Get(string id)
{
return "value";
}
// POST api/<controller>
public void Post(string Name, string Email)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
The first time when the page loads it shows all the candidates perfectly calling the controller IEnumerable Get() method.But when I click save button it can not call the controller api.
I'm not see call:
$resource.$save()
Related
i want to set the flag icon inside the header of my page depending on the selected language, using AngularJS. The language is selected in another .htm-file and its all brought together by AngularJS-routing.
My application uses one controller named "appController". The controller is inserted into the body-tag in "index.html". Inside "index.html" there is a that uses the angular function "setPicUrl()". The value of "appLang" is set by the radio-input in "language.htm", which is inserted into using routing by AngularJS.
The problem is, that the path for the flag icon does not change when i select another language (the variable "appLang" does). The icon is loaded correctly when i start the application.
routing.js
var app = angular.module("angApp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/visualization", {
templateUrl: "htm/visualization.htm",
controller: "appController"
})
.when("/data", {
templateUrl: "htm/data.htm",
controller: "appController"
})
.when("/social", {
templateUrl: "htm/social.htm",
controller: "appController"
})
.when("/about", {
templateUrl: "htm/about.htm",
controller: "appController"
})
.when("/language", {
templateUrl: "htm/language.htm",
controller: "appController"
});
});
controller.js
app.controller("appController", function ($scope, $http, $location) {
$scope.appLang = "english";
$scope.setPicUrl = function () {
if ($scope.appLang === "german") {
return "icons/german.png";
} else if ($scope.appLang === "english") {
return "icons/english.png";
} else {
//TODO Error handling
return;
}
};
index.html
<body ng-app="angApp" ng-controller="appController">
...
<li ng-class="{ active: headerIsActive('/language')}"><a href="#language"><img id="langpic"
ng-src="{{setPicUrl()}}"
class="img-responsive"></a>
...
<div ng-view></div>
</body>
language.htm
<div class="panel panel-default">
<div class="panel-heading">Spracheinstellungen</div>
<div class="panel-body">
<form>
Wählen Sie ihre Sprache aus:
<br/>
<input type="radio" ng-model="appLang" value="german">Deutsch
<br/>
<input type="radio" ng-model="appLang" value="english">Englisch
</form>
</div>
</div>
Thanks for your help! I got a solution:
The problem was, that the controller has been a copy of "appController" in each view and therefore the variables were different ones with the same name and the different views had no access to the same variable.
Now i use a service to share variables with other controllers and use an own controller for each view.
service:
app.factory("sharedProperties", function () {
return {
appLanguage: ""
};
});
langController:
app.controller("langController", function ($scope, sharedProperties) {
$scope.updateSharedProperties = function (){
sharedProperties.appLanguage = $scope.language;
console.log("--> updateSharedProperties(): " + $scope.language);
};
});
headerController:
app.controller("headerController", function ($scope, $http, $location, sharedProperties) {
$scope.setPicUrl = function () {
if (sharedProperties.appLanguage === "german") {
return "icons/german.png";
} else if (sharedProperties.appLanguage === "english") {
return "icons/english.png";
} else {
//TODO Error handling
return;
}
};
});
HTML for changing language (using langController):
<form>
Wählen Sie ihre Sprache aus:
<br/>
<input type="radio" ng-model="language" value="german" ng-click="updateSharedProperties()">Deutsch
<br/>
<input type="radio" ng-model="language" value="english" ng-click="updateSharedProperties()">Englisch
</form>
HTML for displaying flag-icon in header (using headerController):
<li><img id="langpic" ng-src="{{setPicUrl()}}" class="img-responsive"></li>
Try this. You need to execute the setPicUrl:
<input type="radio" ng-click="setPicUrl()" ng-model="appLang" value="german">Deutsch
<br/>
<input type="radio" ng-click="setPicUrl()" ng-model="appLang" value="english">Englisch
Change:
<img id="langpic" ng-src="{{setPicUrl()}}" class="img-responsive">
To:
<img id="langpic" ng-src="icons/{{appLang}}.png" class="img-responsive">
You can use $routeChangeStart or $routeChangeSuccess which are AngularJS built-in functions in bootstrapping function. For example when the route has been changed $routeChangeSuccess will be called automatically and you can change your $rootScope, $localStorage and any other directive's variables.
Try like this code:
//Bootstrapping Func
app.run(function ($window, $rootScope, $location, $route, $localStorage)
{
$rootScope.appLang = "english";
$rootScope.iconLang = "icons/english.png";
// On Route Change End Event
//---------------------------------------------
$rootScope.$on('$routeChangeSuccess', function ()
{
if ($rootScope.appLang === "german") {
$rootScope.iconLang = "icons/german.png";
} else if ($rootScope.appLang === "english") {
$rootScope.iconLang = "icons/english.png";
} else {
//TODO Error handling
}
});
}
Now you can bind the $rootScope.iconLang to the image tag you want like $scope.iconLang.
I am new to angularjs. I want to pass data from html form to another route.
Here is the part of index.html
<div ng-app="myApp" ng-controller="HomeController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div ng-view=""></div>
</div>
</div>
</div>
</div>
Here are the routes
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeController'
});
$routeProvider.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutController'
});
}]);
When the route is / it hits the views/home.html in which it has a form
<form action="#/about" ng-submit="submitData()">
<input type="text" name="address" ng-model="user.address" />
<input type="submit" />
</form>
I have a user service whose implementation is
myApp.factory("user", function () {
return {};
});
I inject user service in HomeController like
myApp.controller("HomeController", function ($scope, user) {
$scope.user = user;
// and then set values on the object
// $scope.user.address = "1, Mars"; // when uncomment this line it can be accessed on AboutController? Why? Otherwise I cannot access user.address
console.log($scope.user);
});
Don note my comment in above code..
and passes user to AboutController like
myApp.controller("AboutController", function ($scope, user) {
$scope.user = user;
// and then set values on the object
$scope.user.firstname = "John";
$scope.user.secondname = "Smith";
console.log($scope.user);
});
Here is the about.html
<p>
{{ user.address }}
</p>
Problem: {{user.address}} doesn't work on AboutController. I can't see any output... But when i remove the comment from above code.. It only displays hardcoded values in the controller What am I missing?
This is the working demo http://ashoo.com.au/angular/#/
At the moment, all your service does is pass a blank object return {}, to any controller into which it is injected. You need a getter/setter approach, so that in your Home view you can set the data, and in your About view you can retrieve it.
So your service could look something like this:
myApp.factory("user", function () {
var dataObj = {};
return {
setData: function(data) {
dataObj.username = data.username;
},
getData: function() {
return dataObj;
}
};
});
Now you can set the data in your Home controller:
myApp.controller("HomeController", function ($scope, user) {
$scope.submitData = function(data) { //pass in ng-model
user.setData(data); //call 'user' service to set data
}
});
And call it from your About controller:
myApp.controller("AboutController", function ($scope, user) {
$scope.user = user.getData(); //Assign
console.log($scope.user.username);
});
And you html would look like:
<form action="#/about" ng-submit="submitData(user.username)">
<input type="text" name="address" ng-model="user.username" />
<input type="submit" />
</form>
On loading '/', I am getting 'content' and 'sidebar'using 'myService' and resolve option in route provider and I can render the 'content' to the template ($scope.contents = content;).
But $scope.sideBar = sideBar; is not working. This is because sideBar is outside the template ?
How can I render sidebar items on loading '/' ? Is it possible to pass this data (sidebar) to the indexCtrl?
app.js
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'contents.html',
controller: 'Myctrl',
resolve: {
content: function(myService){
return myService.getContent();
},
sideBar: function(myService){
return myService.getSideBar();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('Myctrl', function (content, sideBar, $scope) {
$scope.contents = content;
$scope.sideBar = sideBar;
});
myApp.controller('indexCtrl', function($scope) {
});
myApp.service("myService", function () {
this.getContent = function () {
return 'Main contents';
}
this.getSideBar = function () {
return 'side bar'
}
});
index.html
<div ng-app="MyApp" ng-controller="indexCtrl">
<div class="sidebar">
{{sideBar}}
</div>
</div>
<div class="main">
<div ng-view></div>
</div>
</div>
contents.html
<div>{{contents}}</div>
You can inject your myService into your indexCtrl and access the function getSideBar like this
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar();
});
this will get the string from your getSideBar function when your indexCtrl is first initialized. If you do this:
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar;
});
and inside index.html:
<div class="sidebar">
{{sideBar()}}
</div>
The string will update when the data in your service updates.
I am building a note taking application (something like a blog actually with different terms like post=note etc.) to practise my skills in AngularJS and Rails.
There is a sidebar on the left (controller Sidebar.js) which fetches all items form the Rails API and ng-repeats them to a list.
By clicking on one of them, the show.html renders inside ng-show on the right. The show view, has a link that lets you delete the item and then splices it from the sidebar on the left. After much blood, sweat and tears I believe I made it, except one detail: After deletion(=> destroy()) of the item, the wrong index gets deleted from the sidebar. I've tried to make it work with indexOf and then I console.logged the index - it always appears to be -1.
To share the same array of note objects I created a service that does that with a getter and a setter.
How can I delete the right item from the sidebar?
show.html
<div class="row">
<div class="col-lg-10">
<h3>{{ note.title }}</h3>
</div>
<div class="col-lg-2">
<button type="button" ng-click="destroy(note)" class="btn btn-default btn-xs pull-right">
<span class="glyphicon glyphicon-remove"></span></button>
</div>
</div>
<hr/>
<div class="note-description">
{{ note.description }}
<br>
</div>
Sidebar.js
var app = angular.module('notepadApp');
app.controller('SidebarController',
['$scope', '$http', '$routeParams', '$location', 'Note', 'ShareNoteScope',
function($scope, $http, $routeParams, $location, Note, ShareNoteScope) {
$scope.notes = Note.query(function (){
ShareNoteScope.setScope($scope.notes);
});
$scope.getClass = function (path) {
if ($location.path().substr(0, path.length) === path) {
return 'active';
} else {
return '';
}
}
}]
);
sidebar.html
<ul class="nav nav-stacked" ng-controller="SidebarController">
<li ng-repeat="note in notes.notes | orderBy: '-created_at'" class="note-li">
<a href="/notes/{{note.id}}" ng-class="getClass('/notes/{{note.id}}')"
class="" >
{{ note.title }}
</a>
<div ng-repeat="tag in note.tags">
<div class="label">{{ tag }}</div>
</div>
</li>
</ul>
NoteCtrl.js
'use strict';
var app = angular.module('notepadApp');
app.controller('NoteController',
['$scope', '$http', '$routeParams', '$location',
function($scope, $http, $routeParams, $location) {
}]
);
app.controller('NoteShowController',
['$scope', '$http', '$routeParams', '$location', 'Note', 'ShareNoteScope',
function($scope, $http, $routeParams, $location, Note, ShareNoteScope) {
if ($routeParams.id) {
Note.get({id: $routeParams.id}, function(note){
$scope.note = note.note;
});
}
else {
$scope.note = ShareNoteScope.getScope().notes[0].id;
}
//Destroy method for deleting a note
$scope.destroy = function(note) {
Note.remove({id: note.id}, function() {
var index = ShareNoteScope.getScope().notes.indexOf(note);
console.log(index);
ShareNoteScope.getScope().notes.splice(index, 1);
});
$location.path('/notes');
}
}]
);
app.controller('NoteCreateController',
['$scope', 'Note', '$routeParams', '$location','ShareNoteScope',
function($scope, Note, $routeParams, $location, ShareNoteScope) {
$scope.notes = ShareNoteScope.getScope().notes;
$scope.newNote = {};
$scope.createNote = function() {
Note.create($scope.note, function (newNote) {
$scope.notes.unshift(newNote.note);
$scope.newNote = '';
$scope.errors = '';
$location.path('/notes/'+newNote.note.id);
});
}
}]);
models.js
'use strict';
var app = angular.module('notepadApp');
app.factory('Note', ['$resource', function($resource) {
return $resource('/api/notes/:id', { id: "#id" }, {
get: {
method: 'GET'
},
query: {
method: 'GET',
isArray: false
},
create: {
method: 'POST'
}
});
}]);
app.factory('ShareNoteScope', function (Note) {
var $scope;
return {
setScope: function (scope) {
$scope = scope;
},
getScope: function () {
return $scope;
}
}
});
ShareNoteScope.getScope().notes contents
$$hashKey
"object:5"
created_at
"2015-11-29T09:07:18.614Z"
description
null
id
130
tags
[]
title
"5345"
updated_at
"2015-11-29T09:07:18.614Z"
user_id
1
We went to the bottom of this in the chat. And the problem probably had to do with note not referencing an object in ShareNoteScope.getScope().notes. So to get a correct reference, we used filter in this case:
JavaScript
$scope.destroy = function(note) {
Note.remove({id: note.id}, function() {
var res = ShareNoteScope.getScope().notes.filter(function(el){
return el.id == note.id;
});
note = res[0];
var index = ShareNoteScope.getScope().notes.indexOf(note);
console.log(index);
ShareNoteScope.getScope().notes.splice(index, 1);
});
$location.path('/notes');
}
Pass $index in destroy method along with note object
<div class="row">
<div class="col-lg-10">
<h3>{{ note.title }}</h3>
</div>
<div class="col-lg-2">
<button type="button" ng-click="destroy(note,$index)" class="btn btn-default btn-xs pull-right">
<span class="glyphicon glyphicon-remove"></span></button>
</div>
</div>
<hr/>
<div class="note-description">
{{ note.description }}
<br>
</div>
$scope.destroy = function(note, $index) {
Note.remove({id: note.id}, function() {
ShareNoteScope.getScope().notes.splice($index, 1);
});
$location.path('/notes');
}
Try this
I have two angular js controllers. When the click the ng-href link in recorddetails.html,
I am able to see the result binded as "The activity name is Exercise" but the same if I do with ng-click by clicking button with find() in send.html. I am able to see the recorddetails.html but the page is displaying without the data being binded as "The activity name is {{activity}}".I have provided the code belowe for reference.Kindly, provide some valuable solutions.
index.html
<div ng-controller="controllerOne">
<a ng-href="#/recorddetails/100">Running</a>
</div>
recorddetails.html
<div ng-controller="controllerTwo">
<p> The activity name is {{activity}}</a>// The scope name is Exercise
</div>
send.html
<div ng-controller="controllerThree">
<button ng-click="find()">
</div>
JS file
angular.module('exampleapp', ['ngRoute').config(
[ '$provide', '$httpProvider', '$routeProvider', function($provide, $httpProvider, $routeProvider) {
$routeProvider.
when('/recorddetails/:id', {
templateUrl: '/records/recorddetails.html',
controller: 'controllerTwo'
.otherwise({
redirectTo: '/defaultpage'
});
app.controller('controllerOne',
[ '$scope','$location',function($scope,$location) {`enter code here`
}
app.controller('controllerTwo',
[ '$scope','$location',function($scope,$location) {
$scope.activity = "Exercise";
}
app.controller('controllerThree',
[ '$scope','$location',function($scope,$location) {
$scope.find = function(){
$location.path("/recorddetails/100");
}
}
var app=angular.module('binding',['ngRoute'])
app.config(['$routeProvider',function ($routeProvider)
{
$routeProvider
.when('/',
{
templateUrl:'one.html',
controller:'controllerOne'
})
.when('/recorddetails/:id', {
templateUrl: 'recorddetails.html',
controller: 'controllerTwo'
})
.when('/send', {
templateUrl: 'send.html',
controller: 'controllerThree'
})
}])
app.controller('controllerOne',function($scope,$location){
})
app.controller('controllerTwo', function($scope,$location) {
$scope.activity = "Exercise";
})
app.controller('controllerThree',function($scope,$location) {
$scope.find = function(){
console.log('in 3');
$location.path("/recorddetails/100");
}
})
<html ng-app="binding">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
<script src="routefile.js"></script>
</head>
<body>
<div ng-view>
</div>
</body>
</html>