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.
Related
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 }}.
I'm a beginner in AngularJS. I'm here trying to fetch the data from JSON using service and display it. I'm having separate files for controllers, services. I'm unable to find out what I'm doing wrong here. I learned that we return an object in case of factory but, I'm not sure how to return the value when using services. The code that I tried is below.
HTML: I have an index.html file into which I load this HTML:
<div ng-controller="comp">
{{capcino}}
</div>
Controller:
var app = angular.module("retailapp");
app.controller("comp", function($scope, elecservice){
$scope.capcino = elecservice.getval();
});
Service:
angular.module("retailapp").service("elecservice", serjson);
function serjson($http){
var val = "";
this.getval = function(){
$http.get("/elec.json").success(function(res){
val = res.namet;
return val;
});
}
}
Routing:
var app = angular.module("retailapp", ['ngRoute']);
app.config(function($routeProvider){
$routeProvider.when("/computer", {
templateUrl : "computer.html",
controller : "comp"
});
JSON:
{"namet" : "naysan"}
I want to display the value "capcino" in expression in HTML. I'm getting undefined for that value. Kindly help with explanation. Thanks in advance.
Write as follow:
var app = angular.module("retailapp");
app.controller("comp", function($scope, elecservice){
elecservice.getval().then(function(data){
$scope.capcino = data;
});
});
It's a promise so it sets $scope.capcino after it returns. Until that return occurs $scope.capcino is undefined.
var app = angular.module("retailapp");
app.controller("comp", function($scope, elecservice){
elecservice.getval().then(function(data){
$scope.capcino = data;
});
});
Just change your controller to store the data.
$scope.yourFunc = function(params){
YouService.function(params).then(function(result){
$scope.yourVar = result.data;
}
})
}
}
I'm trying to read the following fields (LocationID ..) that I can see in the console when I wrote
console.log($scope.businessInformation);
Console photo capture
Can you help me please?
Thanks
Script.js
app.controller('ProfileController', ['$scope', function($scope) {
$scope.dropLink = '1';
$scope.dropContentLink = '1';
}]);
app.factory('infoService', ['$resource', function($resource){
return $resource('/api/business-information/:id');
}]);
app.controller('BusinessInfoController', ['$scope', 'infoService', function($scope, infoService) {
$scope.isActive = 1;
$scope.is_active_label = 'Active';
$scope.getInfo = function() {
$scope.businessInformation = infoService.query({id: $scope.businessInformation.industryID});
console.log($scope.businessInformation);
};
$scope.updateLabel = function(){
if($scope.isActive === 1){
$scope.is_active_label = 'Active';
}else {
$scope.is_active_label = 'Not Active';
}
};
}]);
routes/api.js
router.route('/business-information/:id')
.get(function(req, res){
conn.query('CALL Inductry_Location_Get(?)', [req.params.id],function(err,info){
if(err) res.send(err);
console.log('Data received from Db:\n');
console.log(info[0]);
return res.send(info);
});
}) ;
module.exports = router;
$resource is awesome because when you call an action like query, the object you receive back will be auto populated as soon as the promise resolves. The problem here is you try to log it right after calling it before the promise gets resolved.
If you want to use it from your controller, you can add your code to the promise which is a property $promise
$scope.getInfo = function() {
$scope.businessInformation = infoService.query({
id: $scope.businessInformation.industryID
});
$scope.businessInformation.$promise.then(function(data) {
// Access data parameter or
console.log(data);
// Use $scope.businessInformation directly since its populated at this point
console.log($scope.businessInformation);
});
};
If you are wanting to use it on your view, you can use the $resolved parameter to know if the data is ready yet.
<div ng-show="businessInformation.$resolved">{{ businessInformation }}</div>
I also want to point out an oddity which is you using $scope.businessInformation before the query is even run. You pass $scope.businessInformation.industryId into the query params.
I have successfully implemented the chatroom in angularjs using node + socket.io
But hope you guys can help me, I am stuck in a situation where I listen to the socket on the clientside
socket.on('new message', function(data){
$scope.messages.push(data);//then run ng-repeat in the template
});
Problem is,
1) if I put the above method inside the controller, the above get reinitialized(multiple listener binds) whenever I open that page again and again(We have multi page app)
or
2) if I put the above method (as the docs says) at a global place I lose the scope of the controller so I cant bind the latest model to the template
Any help??
You could try disconnecting the socket when the $scope is destroyed...
$scope.$on('$destroy', function(){
socket.disconnect();
});
But I like the service based approach...
var SocketService = function(){
var _messages = [];
socket = connectMeToSomeSocket();
socket.on('new message', function(data){
_messages.push(data);
});
Object.defineProperty(this, 'messages', {
get: function(){
return _messages;
}
})
};
Then inject the socketService in your controllers...
angular.controller('SomeCtrl',['$scope', 'socketService', function($scope, socketService){
$scope.socket = socketService;
}])
And use socket.messages in your template...
<li ng-repeat="msg in socket.messages">
If you don't like giving your templates access to the socketService or you don't like Object.defineProperty, then you can add a bindScope method your service...
this.bindScope = function($scope){
var stopWatching = $scope.$watchCollection(function(){ return _messages;}, function(){
$scope.messages = _messages;
});
// may not be necessary as `Scope` prob cleans up after itself
$scope.$on('$destroy', stopWatching);
};
And use it in your controllers...
socketService.bindScope($scope);
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 +
'¶meter2=' + 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;
}
}
});