Data not passing between Controllers - angularjs

Hi I am trying to pass data from one Controller to another but the data is not displaying on the other end of UI .
this is my service code :-
app.factory('ServiceF', function($rootScope) {
var service = {};
service.data = false;
service.sendData = function(data){
this.data = data;
$rootScope.$broadcast('data_shared');
};
service.getData = function(){
return this.data;
};
return service;
});
Controller 1 Code :-
app.controller('Ctrlone', ["$scope", "ServiceF", function ($scope, ServiceF) {
$scope.Info= {};
$scope.ser= function(){
ServiceF.sendData($scope.Info);
console.log($scope.Info);
};
}]);
The $scope.Info data is coming successfully here from other source which I haven't posted . But it is coming.
Controller 2 :-
app.controller('Ctrltwo', ["$scope" ,"ServiceF",
function($scope , ServiceF) {
$scope.Info= '';
$scope.$on('data_shared',function(){
var good = ServiceF.getData();
$scope.Info = good;
});
}]);
UI where I want to display info :-
<div class="col-sm-8">
<h1 class="mainTitle">Ok Start </h1>
<h2>{{good}}</h2>
</div>
Button click function from 1st UI :-
<label class="cardlabel" style="width:11vw" ui-sref="uitwo" ng-click="ser()">Send</label>
Now where am I going wrong ? Info is not displaying on 2nd UI. And how can I check if data is passing on Service ?

You have no attribute named good in your scope. So {{ good }} will always be empty.
The scope attribute is named Info. So you want {{ Info }}.

Related

AngularJs, Passing optional parameters to the URL based on user input

I am trying to consume my ASP.NET Web API using AngularJs. The problem is that i want to pass optional parameters to the url based on the user input(2 Html Text Boxes) but i don't know how.
This is my ASP.NET Web API Controller
[Route("api/JobShow/{keyword}/{location}")]
public class JobShowController : ApiController
{
[HttpGet]
public PageResult<sp_JobSearch_Result> Get(ODataQueryOptions<sp_JobSearch_Result> options, string keyword = null, string location = null)
{
ODataQuerySettings settings = new ODataQuerySettings()
{
PageSize = 20
};
JobWindow obj = new JobWindow();
IQueryable results = options.ApplyTo(obj.showJobs(keyword, location).AsQueryable(), settings);
return new PageResult<sp_JobSearch_Result>(
results as IEnumerable<sp_JobSearch_Result>,
Request.GetNextPageLink(),
Request.GetInlineCount());
}
}
And this is my AngularJS controller
angular.module('JobSearch.SiteController', []).controller('JobSearchCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/api/JobShow').success(function (data) {
$scope.model = data;
});
}]);
Example of the url then would be .../api/JobShow/Java/Toronto. Thank you all.
You can try ngResource !
You first need to include ng-resource
<script src="angular.js">
<script src="angular-resource.js">
You can get it via Bower or CDN, or whichever way you got AngularJS.
HTML:
<body ng-app="MyApp">
<div ng-controller="MyCtrl">
<label>Keyword: <input type="text" ng-model="keyword" /></label>
<label>Location: <input type="text" ng-model="location" /></label>
<button ng-click="getJobShowPage(keyword, location)">Search</button>
</div>
</body>
Controller:
angular
.module('MyApp', ['ngResource']) // Include the ngResource module here
.controller('MyCtrl', ['$scope', '$resource', function($scope, $resource){
// Create the $resource
var JobShowPage = $resource('/api/JobShow/:keyword/:location', {keyword: "#keyword", location: "#location"})
// Make a scope function to use the resource properly
$scope.getJobShowPage = function(keyword, location) {
var parameters = {};
if (keyword) {
parameters["keyword"] = keyword;
if (location) {
parameters["location"] = location;
}
}
return JobShowPage.get(parameters);
};
}]);
Input/Outputs:
When the user enters nothing and clicks 'Search', the HTTP request would be /api/JobShow
If only the keyword is entered, the HTTP request would be /api/JobShow/{{keyword}}
If both the keyword and location is entered, the HTTP request would be /api/JobShow/{{keyword}}/{{location}}
If only the location is entered (no keyword), the HTTP request would be the vanilla one /api/JobShow
You can consume the return value of the $resource query like a promise:
JobShowPage.get(parameters).$promise.then(function(response){
// Do Stuff
$scope.model = response.data;
});
by callbacks:
JobShowPage.get(parameters, function(err, response){
// Do Stuff
$scope.model = response.data;
});
Or auto unwrap it:
// This works, but it's asynchronous
// Useful if consuming directly from the Angular Template
$scope.model = JobShowPage.get(parameters);
Based on your code, I'm going to assume you have 2 textboxes and a search button, and when the search button is pressed, you want to call your GET endpoint. For this scenario, what you'll want to do is bind the textbox inputs to your scope and bind the search button using ng-click to a function in your scope that will call your endpoint. It might look something like this:
controller
angular.module('JobSearch.SiteController', [])
.controller('JobSearchCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.getResults= getResults;
function getResults() {
$http.get('/api/JobShow/' + $scope.keyword + '/' + $scope.location).success(function (data) {
$scope.model = data;
});
}
}]);
html
<div ng-controller="JobSearchCtrl">
<input type="text" ng-model="keyword">
<input type="text" ng-model="location">
<button type="button" ng-click="getResults()">Search</button>
</div>

Update $scope variable that is used in ng-repeat, from other controller

I have a controller HomeworkPageController where I get all the topics from MongoDB using method getAllMainTopics from TopicService. $scope.topics is then used to show all topics. I have a button that open a modal where a new topic is add in MongoDB. The modal is using another controller AddTopicController. How can I update $scope.topics from HomeworkPageController in AddTopicController ? I want to do this because after I close the modal, the list of all topics should be refreshed, it must contain the topic that has been added. I tried to use HomeworkPageController in AddTopicController and then call the method getAllMainTopics but the $scope.topics from html is not updated. Thanks.
Here is HomeworkPageController:
app.controller('HomeworkPageController', ['$scope','TopicService',
function ($scope, TopicService) {
$scope.topics = [];
$scope.getAllMainTopics = function () {
TopicService.getAllMainTopics('homework')
.success(function(data) {
$scope.topics = data;
}
$scope.addTopic = function () {
ModalService.openModal({
template: "templates/addTopic.html",
controller: 'AddTopicController'
});
}
]);
Here is AddTopicController:
app.controller('AddTopicController', ['$scope','$controller', '$timeout','TopicService', '$modalInstance',
function ($scope, $controller, $timeout,TopicService, $modalInstance) {
var homeworkPageController = $scope.$new();
$controller('HomeworkPageController',{$scope : homeworkPageController });
$scope.save = function() {
TopicService.saveTopic(data)
.success(function(result){
homeworkPageController.getAllMainTopics();
$modalInstance.close();
})
}
}]);
Here is the view where I use $scope.topics:
<div class="homework-content-topic-list" ng-repeat="topic in topics">
<label> {{ topic.subject }} </label>
</div
You should probably keep your list of topics in a service and then inject that service into both controllers. This way you would be able to access and update the topics in both of your controllers. It could look something like
app.controller('HomeworkPageController', ['$scope','TopicService',
function ($scope, TopicService) {
$scope.topics = TopicService.topics;
// Do stuff here
]);
Then you just need to modify your TopicService to have it's methods work on the stored object.
you can solve this by two methods
1)look at the example given in ui-bootstrap's website. They have given an example that will suit your requirement - plunker. There are three items in the modal - item1, item2, item3. If you select one of those items and click 'ok', the selected item is sent to the main controller through "resolve" attribute in the $scope.open function.
2)You can write a custom service that acts as a bridge to the two controllers and you can write getter and setter methods in the service.
angular.module('app').service('popupPageService', function() {
var topics;
var setDetails = function(param) {
topics = param;
};
var getDetails = function() {
return topics;
};
return {
setDetails: setDetails,
getDetails: getDetails,
};
});
call the setDetails function in the AddTopicController and once when you come out of the modal, update your $scope.topics in HomeworkPageController by pushing the new value added (getDetails)

angularJS controllers and PDF

I work with angularJS and I have some difficulties with controllers.
I have one page on on this page I have two controllers one to receive data from a web service and one to display the data on pdfViewer.
My idea is to start the second controller after the first controller have receive the datas because now it's seems that the two controller start at the same time so nothing is display.
Here my code for the view :
var seeCv = angular.module('myApp', ['ngPDFViewer']);
seeCv.controller('TestCtrl',function($http){
$http.get('some url').success(function(data){
datas = data;
});
});
seeCv.controller('VisuCvCtrl',['$scope','PDFViewerService',function($scope,pdf){
$scope.pdfURL = datas;
$scope.instance = pdf.Instance("viewer");
$scope.nextPage = function(){
$scope.instance.nextPage();
};
$scope.prevPage = function(){
$scope.instance.prevPage();
};
$scope.pageLoaded = function(curPage, totalPages){
$scope.currentPage = curPage;
$scope.totalPage = totalPages;
};
}]);
<div ng-controller="TestCtrl" >
<div class="container" ng-controller="VisuCvCtrl">
<button ng-click="prevPage()"><</button>
<button ng-click="nextPage()">></button>
<br>
<span>{{currentPage}}/{{totalPage}}</span>
<br>
<pdfviewer src="{{pdfURL}}" on-page-load='pageLoaded(page,total)' id="viewer"></pdfviewer>
</div>
</div>
PS: I tried to make the web service call on the second controller but there was a error with the $http.
Each controller has its own scope, you are trying to reach testController scope from VisuCtrl, actually you are trying to use parent's controller scope from child controller. You can do it this way:
seeCv.controller('TestCtrl',function($http){
$http.get('some url').success(function(data){
datas = data;
});
});
seeCv.controller('VisuCvCtrl',['$scope','PDFViewerService',function($scope,pdf){
$scope.pdfURL = $scope.$parent.datas;
...
}]);
Anyhow, I suggest a service in order to fetch the data (This way you can reuse the service get function in others controllers as well).
Controller will use the service to get the data and put it on scope so the view can use this data.
I found a way to do it in the same controller :
seeCv.controller('VisuCvCtrl',['$scope','$http','PDFViewerService',function($scope,$http,pdf){
var promise = $http.get('some url').success(function(data){
datas = data;
});
promise.then(
function(display){
$scope.pdfURL = datas;
$scope.instance = pdf.Instance("viewer");
$scope.nextPage = function(){
$scope.instance.nextPage();
};
$scope.prevPage = function(){
$scope.instance.prevPage();
};
$scope.pageLoaded = function(curPage, totalPages){
$scope.currentPage = curPage;
$scope.totalPage = totalPages;
};
});
}]);
But the thing is now I have this kind of error repeating each 10 seconds.
error: [$interpolate:interr] errors.angularjs.org/1.2.9/$interpolate/interr?p0=%7B%7BpdfURL%7D%7D…2500%2500%2500%2500%2500%2500%2500%2500%2500%2500%2500%2500%2500%2500%2500
at Error (native)
at code.angularjs.org/1.2.9/angular.min.js:6:449
at Object.$get.s (https://code.angularjs.org/1.2.9/angular.min.js:73:497)
at h.Bd.$get.h.$digest (code.angularjs.org/1.2.9/angular.min.js:100:171)
at h.Bd.$get.h.$apply (code.angularjs.org/1.2.9/angular.min.js:103:100)
at HTMLButtonElement. (code.angularjs.org/1.2.9/angular.min.js:179:65)
at code.angularjs.org/1.2.9/angular.min.js:27:208
at q (code.angularjs.org/1.2.9/angular.min.js:7:380)
at HTMLButtonElement.Zc.c (code.angularjs.org/1.2.9/angular.min.js:27:190) angular.js:9419
(anonymous function)
And I really don't know what it is.

How to retain the variable's value of JSP using AngularJS

I am new to AngularJS. I am trying learn to pass the value of a variable to the angularJS.
But for some unknown reason, I am not being able to do.
Below is the .jsp page which I think is correct:
<body >
<div ng-controller="customersController">
<label>Value</label>
<input type="text" ng-model=something></input>
<button ng-click="punchIt()">click me!</button>
<br>Obtained value : {{ value }}
</div>
</body>
In the respective .js page, value passed from .jsp file is not getting retained.The first alert function should return assumed : something's value,but it is returning assumed : undefined.
Below is the .js file:
var myApp = angular.module("getInfo", []);
myApp.controller("customersController", function($scope, $http){
$scope.punchIt = function ($scope, $http) {
var data = {Value: $scope.something};
alert("assumed : "+ $scope.something);
$http.post("http://localhost:8082/HelloWorldWS/services/HelloWorldImpl",data)
.success(function (data, status, header) {
alert("in success " + data);
$scope.value = data;
}).error(function (data) {
alert("in error method " + status);
$scope.value = "error "+ data;
});
};
});
Please suggest some way out.
Thanks.
You are expecting two variables ($scope and $http) in your punchIt() function declaration but not passing these when you call it on button click. Thus inside your punchit() function, both $scope and $http variables would be initialized to nothing (read undefined).
You actually dont need to pass these parameters to your function. Your controller already has these services injected in it via your controller declaration.
Also declare/initialize the name variable in your controller. Else, if you do not enter anything in the input field and try to access it in your $scope, you will retrive it as undefined.
Your code changes would look as below:
myApp.controller("customersController", function($scope, $http){
$scope.name=null;
//OR $scope.name='';
$scope.punchIt = function () {
...
}
}

Execute scope function from service parameter

I am trying to create a service when I can set my formSubmit.
For example. In controller A I call "service.setFormSubmit(doThis(obj))" and in controller B I call "service.getFormSubmit()". Where it will execute the function doThis(obj) in controller B.
UPDATE - Re-formulated question.
I have 1 view where I want to edit or create a category. This means I need a dynamic ng-submit. I want to to this in the controller. So like this:
$scope.editCategory = function(obj) {
$scope.formSubmit = 'editCategory'
}
And on the create I want to change the formSubmit var to createCategory of course.
So I can make a difference between creating and editing the category.
Is this possible? Would be really nice if someone has a way to do this..!
Thanks in advance!
Instead of passing around strings which need to be eval'ed, use the service to share functionality directly between controllers.
The service can be dirt-simple:
.factory('MyService', function(){
var service = {};
return service;
});
Once injected and assigned to scope variables in both controllers you have an intermediary unit which can act as a modifiable channel for cross-controller collaboration.
.controller('FirstController', function($scope, MyService){
$scope.service = MyService;
})
.controller('SecondController', function($scope, MyService){
$scope.service = MyService;
$scope.service.create = function(obj){
console.log('Creating');
}
$scope.service.edit = function(obj){
console.log('Editing');
}
})
From the scope of FirstController, you can now call the function also available on the scope of SecondController:
<div ng-controller="FirstController">
<input type="checkbox" ng-model="button.type"> Toggle create/edit<br/>
<button ng-if="button.type" ng-click="service.create(obj)">Create</button>
<button ng-if="!button.type" ng-click="service.edit(obj)">Edit</button>
</div>
Demo
If you aren't reloading the page you can create an encapsulated variable in your service. Your set call would assign the value passed to that variable and your get call would return that variable to the caller.
One way I have achieved passing the data is to submit the form using the service and return a Json result to the service. Store the Json object in the encapsulated variable on the return and then pass a success or failure to the controller. When successful, let the controller redirect the view which will redirect using angular routing and ng-view. Once the new view, along with the new controller is loaded into the page, you can call the variable in your service to retrieve the data on the next controller.
Example Code:
app.factory('service', function ($q, $http) {
var savedData;
return {
loadData: function() {
return data;
},
search: function (parameters) {
var searchURL = '/MVCController/Search?parameter1=' + parameters.one +
'&parameter2=' + parameters.two;
var deferred = $q.defer();
$http.get(searchURL).success(function (data) {
savedData = data;
deferred.resolve(true);
}).error(function(data) {
data = 'An error occurred while searching: ' + data;
savedData = data //(if you want to save the error)
deferred.reject(data);
});
return deferred.promise;
}
}
});

Resources