I tried a lot and could not find proper answer which can solve my problem. Hope someone will help me out.
app.controller('MainController', ['$scope', 'MainService', 'CONSTANTS', '$routeParams', '$location',
function($scope, MainService, CONSTANTS, $routeParams, $location) {
$scope.indexAction = function() {
MainService.query({format: 'json'}, function(data){
$scope.data = data;
**This data still there when viewAction get call.**
});
}
$scope.newAction = function($event) {
$scope.isNew = true;
angular.isDefined($event)? $event.preventDefault() : false;
if(angular.isDefined($event)) {
var postData = $('#form').serialize();
MainService.save({format: 'json'}, postData, function(data, responseHeader){
var loc = responseHeader('location');
var r = /\d+/;
var dataId = loc.match(r);
$scope.viewAction(dataId[0]);
});
}
else {
$location.path('new');
}
}
$scope.viewAction = function(ObjOrId) {
var dataId = null;
if(angular.isObject(ObjOrId)) {
dataId = ObjOrId.id;
$scope.data = ObjOrId;
$location.path('view/'+dataId);
}
else {
dataId = ObjOrId;
MainService.get({Id: ObjOrId, format: 'json'}, function(data) {
$scope.data = data;
$location.path('view/'+dataId);
});
}
}
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
});
}
]);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/new', {
templateUrl: 'abc.html',
controller: 'MainController'
}).
when('/view/:Id', {
templateUrl: 'xyz.html',
controller: 'MainController'
}).
otherwise({
templateUrl: 'list.html'
})
$locationProvider.html5Mode({
enabled: false
});
}
])
The data which comes in list.html with the help of indexAction that still exists when view route called and I am calling viewAction and loading data from ajax but that new data does not get updated in the view.
Please help!!
Your location.path looks like $location.path('new') when they should look like $location.path('/new');
Your other one looks like $location.path('view/'+dataId) when it should look like $location.path('/view'+ dataId);
I found the answer, I was using ng-model in form template and that was updating the $scope.data object without submitting the form itself, So i changed input directive ng-model to ng-value and while migrating to view template there i am able to get the data.
Related
I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}
I triggered the %a{"ng-click"=>"get_destinations(city)"}
However, it should redirect me to "destinations" controller, but it didn't
and there is no error in webconsole, what's going on ?
welcome.js.erb
var App = angular.module('App', ['ngRoute']);
App.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/depart_from/:id',
{
templateUrl: "<%= asset_path('promotion_destinations.html') %> ",
controller: 'destinations'
}
)
.otherwise({ redirectTo: '/depart_from/:id' });
}]);
App.controller("departure_cities", function($scope, $location, $http) {
$http.get("/promotion.json")
.success(function (response) {
$scope.departure_cities = response;
});
$scope.get_destinations = function(id) {
return $location.url("/depart_from/" + id);
};
});
App.controller("destinations", function($scope, $location, $http) {
$http.get("/another_city.json")
.success(function (response) {
$scope.destinations = response;
});
});
Your default controller is destinations in the $scope of destinations controller no any method like get_destinations .
Put your method in side destinations controller it will work if every thing is fine.
Well if you can link the html generated (the one that see the browser, not the server template) that would help.
However i still see an error for me in the HTML (or it's a naming problem)
get_destinations(city)
And in the javascript :
$scope.get_destinations = function(id)
Maybe you wanted to do this ?
get_destinations(city.id)
Im a newbie in angular, trying to learn the language.
Got the following code: http://plnkr.co/edit/fuVb0mzhmDCKr1xKp7Rn?p=preview
Have a tab:
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when
('/jobs', {templateUrl: 'jobs-partial.html', controller: JobsCtrl }).
when
('/invoices', {templateUrl: 'invoices-partial.html', controller: InvoicesCtrl }).
when
('/payments', {templateUrl: 'payments-partial.html', controller: PaymentsCtrl }).
otherwise({redirectTo: '/jobs'});
// make this demo work in plunker
$locationProvider.html5Mode(false);
}]);
I would like to be able to access the selected tab from one the panel. How can I send parameters to the tab controllers?
Create a service that will set a value and return it:
.service('shared', function() {
var myValue;
return {
setValue: function(value) {
myValue = value;
},
getValue: function() {
return myValue;
}
}
});
Then inject it into both your controllers:
.controller('Ctrl1', ['shared', function(shared)......
.controller('Ctrl2', ['shared', function(shared)......
And then set the value from Ctrl1:
shared.setValue('somevalue');
And in Ctrl2 you can just retrieve the value:
var mySharedValue = shared.getValue();
You can create a Service or Factory, inject that in to your TabsCtrl, save the currentTab state in that service in ng-click. Inject the same service in your Page controllers like JobsCtrl
app.factory('MyService',function(){
var currentTab ;
return {
setCurrentTab : function(tab){
currentTab = tab;
},
getCurrentTab : function(tab){
return currentTab;
}
};
});
Update your TabsCtrl like below
function TabsCtrl($scope, $location, MyService) {
// removing other code for brevity
$scope.selectedTab = $scope.tabs[0];
// saving the default tab state
MyService.setCurrentTab($scope.tabs[0]);
$scope.setSelectedTab = function(tab) {
$scope.selectedTab = tab;
// saving currentTab state on every click
MyService.setCurrentTab(tab);
}
}
In your JobsCtrl, inject the same MyService and retrieve the cached tab state like below
function JobsCtrl($scope, MyService) {
var currentTab = MyService.getCurrentTab();
alert(currentTab.label);
}
Here's an updated Plunker with the above changes.
i am just learning basics of angular and today it started to change my app using a factory to get data and implementing route provider ! So far everything works fine! But when I try to add data on another view and head back to my list view scope is reloaded again from factory and no added data shows up.
My approach won't work because each time change my view I will call my controller which reloads data from factory! What can I do to make my Add template will work and changes data everywhere else too.
Maybe somebody can give me a tip how to cope with this problem ?
script.js
var app = angular.module('printTrips', ['ngRoute']);
app.factory('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
app.controller('TripController', function($scope, $filter, tripFactory) {
$scope.trips = [];
tripFactory.getTrips().success(function(data){
$scope.trips=data;
var orderBy = $filter('orderBy');
$scope.order = function(predicate, reverse) {
$scope.trips = orderBy($scope.trips, predicate, reverse)};
$scope.addTrip = function(){
$scope.trips.push({'Startdate':$scope.newdate, DAYS: [{"DATE":$scope.newdate,"IATA":$scope.newiata,"DUTY":$scope.newduty}]})
$scope.order('Startdate',false)
$scope.newdate = ''
$scope.newiata = ''
$scope.newduty = ''
}
$scope.deleteTrip = function(index){
$scope.trips.splice(index, 1);
}
});
});
view.js
app.config(function ($routeProvider){
$routeProvider
.when('/',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view1',
{
controller: 'TripController',
templateUrl: 'view1.html'
})
.when('/view2',
{
controller: 'TripController',
templateUrl: 'view2.html'
})
.when('/addtrip',
{
controller: 'TripController',
templateUrl: 'add_trip.html'
})
.otherwise({ redirectTo: 'View1.html'});
});
Here is my plunker
Thanks for your help
You should use Service instead of Factory.
Services are loaded each time they are called. Factory are just loaded once.
app.service('tripFactory', function($http) {
return{
getTrips : function() {
return $http({
url: 'trips.json',
method: 'GET'
})
}
}
});
I am unable to understand the errors of Angular JS. I am trying to build a factory but it keeps on giving me the following error in firefox console.
Error: [ng:areq] http://errors.angularjs.org/1.2.9/ng/areq?p0=hospitalController&p1=not%20a%20function%2C%20got%20undefined
My Code is
index
<div class="main ng-scope" ng-view="">
partial
<button data-ng-click="ShowStaff()">show</button>
app.js
var myApp = angular.module('myApp', [
'ngRoute',
'artistControllers'
]);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/list', {
templateUrl: 'partials/list.html',
controller: 'ListController'
}).
when('/hospital', {
templateUrl: 'partials/hospital.html',
controller: 'hospitalController'
}).
when('/docter', {
templateUrl: 'partials/docters.html',
controller: 'docterController'
}).
when('/details/:itemId', {
templateUrl: 'partials/details.html',
controller: 'DetailsController'
}).
otherwise({
redirectTo: '/hospital'
});
}]);
controller.js
var artistControllers = angular.module('artistControllers', ['ngAnimate']);
artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
$http.get('js/data.json').success(function(data) {
$scope.artists = data;
$scope.artistOrder = 'name';
});
// Starting Factory for Doctor and hospital relationship
artistControllers.factory( 'StaffFactory','$http',function(){
var factory = {};
$http.get('js/hospital.json').success(function(data) {
factory.hospitals = data;
//$scope.hospitalOrder = 'name';
});
$http.get('js/docters.json').success(function(data) {
factory.doctors = data;
//$scope.hospitalOrder = 'name';
});
factory.getDocs = function(){
return factory.doctors;
};
factory.getHos= function(){
return factory.hospitals;
};
factory.getStaff = function(){
var result=[];
var endres=[];
angular.forEach(factory.hospitals, function(hospital){
result=[];
angular.forEach(factory.doctors,function(doc){
if(doc.id==hospital.id)
{
result.push(doc);
}
});
endres.push([hospital,result]);
});
return endres;
}
return factory;
});
artistControllers.SimpleController=function($scope,StaffFactory){
$scope.customers=[];
$scope.hospitals=[ ];
$scope.doctors=[];
$scope.staff=[];
init();
function init()
{
$scope.doctors=StaffFactory.getDocs();
$scope.hospitals=StaffFactory.getHos();
}
$scope.ShowStaff = function()
{
$scope.staff=StaffFactory.getStaff();
}
};
// Ending Factory for Doctor and hospital relationship
}]);
In addition to the actual error explained by #dave, if you want eror messages to be more explicit without having to follow a link, you should use angular.js instead of angular.min.js (the minimized one) for your development environment.
If you follow the link in the error, you will see
Argument 'hospitalController' is not a function, got undefined
It sounds like you have in your html somewhere:
ng-controller="hospitalController"
but you haven't created a controller with that name.