Very new to Angular.js and having an issue that I cannot figure out. This is my html
<user-details></user-details>
This is my angular code:
angular.
module('rtcTimesheet').
component('userDetails', {
template:
'<p>Hi {{$ctrl.username}}</p>',
controller: function UserDetailsController(globalDataService,$http) {
if(globalDataService.getServicePath()) {
try {
this.username="name here";
this.userId=""
$http({
method: 'GET',
url: globalDataService.getServicePath()+'login.php',
params: {
t: "log",
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("<p>ERROR: " + response.data.ErrorMessage+"</p>");
} else {
username=response.data.name;
userId=response.data.id;
$("#debug").append(this.username);
}
},function (err){
$("#debug").append("ERROR http: "+err.status);
});
} catch(err) {
$("#debug").append("CATCH ERROR: "+err.status+"<br/>");
}
} else {
$("#debug").append("<p>Unable to get service path...</p>");
}
}
});
I know the data is being returned correctly, as I can output it using the
$("#debug").append(this.username)
When the page is loaded it just displays the initial 'name here'. Probably has something to do with the slight delay of getting the data back from the database, but no idea how to get around this?
Your variable referance is incorrect. Check the code bellow to use controllerAs refferance with _self.
angular.
module('rtcTimesheet').
component('userDetails', {
template:
'<p>Hi {{$ctrl.username}}</p>',
controller: function UserDetailsController(globalDataService,$http) {
if(globalDataService.getServicePath()) {
try {
var _self = this;
_self.username="name here";
_self.userId=""
$http({
method: 'GET',
url: globalDataService.getServicePath()+'login.php',
params: {
t: "log",
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("<p>ERROR: " + response.data.ErrorMessage+"</p>");
} else {
_self.username=response.data.name;
_self.userId=response.data.id;
$("#debug").append(_self.username);
}
},function (err){
$("#debug").append("ERROR http: "+err.status);
});
} catch(err) {
$("#debug").append("CATCH ERROR: "+err.status+"<br/>");
}
} else {
$("#debug").append("<p>Unable to get service path...</p>");
}
}
});
Related
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -
Error: $injector:modulerr
Module Error
Then I tried searching for the why the module won't load but with no luck.
main.js /*File where app module is declared*/
var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);
I tried injecting the dependency for the controller files.
Controllers:
Link Controller
var app = angular.module('app');
app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*First AJAX request which gets all the links and categories for the user*/
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
$scope.getUser = function () {
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
};
$http({
method: 'GET',
url: '/links'
}).then(function successCallback(response) {
this.orderProp = 'age';
/*the response is saved in scope variables*/
$scope.links = response.data[0];
$scope.categories = response.data[1];
$scope.categorytolink = response.data[2];
}, function errorCallback(response) {
console.log('There was a problem! Refresh!');
});
/*AJAX request for getting the recommendations according to the most viewed stars*/
$http({
method: 'GET',
url: '/recommendations/top'
}).then(function successCallback(response) {
$scope.recommendations = response.data;
}, function errorCallback(response) {
});
/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
$http({
method: 'GET',
url: "/proxy",
headers: {
"X-Proxy-To": link.rss_link
}
}).then(function successCallback(response) {
/*AJAX request: add a star to the link*/
$http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {
// Manually increment star for link just clicked
var $data;
$data = data.data;
$scope.link = $data;
console.log('200 OK! Star added');
}, function errorCallback() {
console.log('Error!');
});
/*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/
$myXml = response.data;
$xmlObj = $.parseXML($myXml);
$newsItems = [];
$channelImage = $($xmlObj).find("channel>image");
/*the information of the link is sorted */
$linkData = {
"title": $channelImage.find("title").text(),
"link": $channelImage.find("link").text(),
"imgurl": $channelImage.find("url").text()
};
/*the data is sorted below*/
$.each($($xmlObj).find("item"), function (index, value) {
$newsItems.push({
"title": $(value).find("title").text(),
"description": $(value).find("description").text(),
"link": $(value).find("link").text(),
"date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
"time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
"guid": $(value).find("guid").text()
})
});
$scope.newsItems = $newsItems;
$scope.linkData = $linkData;
}, function errorCallback(response) {
});
};
/*Create a category private to the user*/
$scope.create_category = function (category) {
/*AJAX request: adds a new category*/
$http.post('/categories/new', {'category': category}).then(function successCallback(response) {
/*AJAX request: Updates the categories for the use of new category*/
$http({
method: 'GET',
url: '/categories'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
});
}, function errorCallback(response) {
});
};
}]);
User Controller
var app = angular.module('app');
app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
$scope.dzOptions = {
paramName: "file",
dictDefaultMessage: "<h4><i class='fa fa-camera'></i> <b>Upload</b></h4>",
createImageThumbnails: false,
autoDiscover: false
};
$scope.dzCallbacks = {
'sending': function (file, xhr, formData) {
formData.append('_token', $('#csrf-token').val());
},
'success': function (file, response) {
$scope.user = response;
$.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
}
};
/*Update user info*/
$scope.updateUser = function () {
/*AJAX request: update user info*/
$http.post('/users/update', {
'name': $scope.user.name,
'username': $scope.user.username,
'email': $scope.user.email
}).then(
function successCallback(data) {
$scope.user = data;
$.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
console.log('200 OK! User updated');
}, function errorCallback() {
console.log('Error!');
});
};
}]);
Article Controller
var app = angular.module('app');
app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*Populates the comments for particular
* */
$scope.populatecomments = function (newsItem) {
$http({
method: 'GET',
url: '/articles/' + newsItem.guid + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
}, function errorCallback(response) {
});
};
$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
if ($scope.txtcomment != '') {
$scope.data.push({
"comment": $scope.txtcomment,
"guid": newsItem.guid
});
$http.post('/comments/new', {
"comment": $scope.txtcomment,
"guid": newsItem.guid
}).then(function successCallback() {
var encodedURI = encodeURIComponent(newsItem.guid);
$http({
method: 'GET',
url: '/articles/' + encodedURI + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
$scope.txtcomment = "";
}, function errorCallback(response) {
});
}, function errorCallback() {
console.log('Error comment!');
});
}
};
$scope.savearticle = function (newsItem) {
$http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
/*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
}, function errorCallback(response) {
});
}
/**
* The saved articles by the user will be retrieved when a button clicked
*/
$scope.getSavedArticles = function () {
/*AJAX request: retreive the saved the saved articles for the user*/
$http({
method: 'GET',
url: '/saved-articles'
}).then(function successCallback(response) {
$scope.linkData = null;
$scope.newsItems = response.data;
}, function errorCallback(response) {
});
};
}]);
HELP needed!
Yo do not need to declare module in each controller file. Remove the line in each controller
var app = angular.module('app');
You are injecting controller in you module like dependency.
Change your main.js file to this:
var app = angular.module('app', ['ngRoute','thatisuday.dropzone']);
#Sajeetharan is right you do not need module declaration in all controllers.
Since you are using laravel according to your comment. ( It will conflict with your blade template because both use same {{ }} for variables )
There are two ways to do this:
Change the Angular Tags
var app = angular.module('app', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
Now Laravel will use the {{ variableName }} and Angular will use <%
variableName %>.
Change the Laravel Blade Tags
Blade::setContentTags('<%', '%>');// for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>');// for escaped data
Variables will be: <% $variable %>. Comments will be: <%-- $variable
--%>. Escaped data will look like: <%% $variable %%>.
You can check this Tutorial for more info.
I've just started getting into using Angular and having an issue displaying a single record that is being returned from using $http (get). I'm getting the data back correctly. This is the html I've got....
<div ng-controller="UserDataController as udCtrl">
Name: {{udCtrl.user.name}}
</div>
<div id="debug" style="margin-top:24px;border:solid 1px #900;background:#efefef;min-height:100px"></div>
have also tried and a couple of other variations...
Name: {{udCtrl.name}}
Javascript:
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var user=this;
user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();
This is what is returned in JSON format and I can see this in the little debug area I created.
{"data":{"id":"1","name":"Joe Bloggs"}
if I change the html to use the code below it works.
<div ng-controller="UserTest as udCtrl">
Name: {{udCtrl.user.name}}
</div>
I just cannot see where I'm going wrong and why it will not display the returned name.
Define the user variable on $scope and access it with $scope.user. You are having referance problem.
Example
//Define user variable like this.
$scope.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
$scope.user=response.data;
}
}
EDIT
If you want to use udCtrl referance define variable under thisvariable on controller.
//Define user variable like this.
var ctrl = this;
ctrl.user = {};
//On response -->
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
ctrl.user=response.data;
}
}
EDIT 2 FOR ABSOLUTE ANSWER
(function() {
var app = angular.module('rtcTimesheet', []);
var servicePath="/angular/";
$("#debug").append("Starting...<br/>");
app.controller("UserDataController",["$http",function($http){
var udCtrl=this;
udCtrl.user=[];
$http({
method: 'GET',
url: servicePath+'login.php',
params: {
un: "username",
pwd: "123456789"
}
}).then(function(response){
if(response.data.hasOwnProperty("HasError")) {
$("#debug").append("ERROR: " + response.data.ErrorMessage);
} else {
$("#debug").append("Data: " + JSON.stringify(response.data));
udCtrl.user=response.data;
}
},function (err){
alert("ERROR: "+err.status); //data, status, headers, config, statusText
});
}]);
app.controller("UserTest",function(){
this.user=users;
});
var users = {
id: '1',
name: 'Joe Bloggs'
};
})();
I am passing an object to angular factory it is throwing error.
factory:
visitorApp.factory('loginRepository', function ($resource) {
return {
VerifyVisitor: $resource('/api/VisitorWeb/VerifyLogin', {}, {
query: { method: 'POST', params: {loginModel:loginModel}, isArray: true }
})
};
});
The complex object i am trying to pass is loginModel.
From controller call to factory.
visitorApp.controller('LoginController', function ($scope,$location,$route,loginRepository) {
$scope.submit = function (isValid) {
if (isValid) {
var loginModel = {
UserName: $scope.UserName,
PassWord: $scope.Password
};
var response = loginRepository.VerifyVisitor.query(loginModel);
alert(response);
}
}
});
Error: loginModel is not defined
Web Api Method which is being called.
[HttpPost]
public string VerifyLogin(UserLoginDomainModel loginModel)
{
var msg = _loginService.Login(loginModel);
return msg;
}
Is it the right way of using $resource to post a request and pass complex object.
Your service should look something like this:
visitorApp.factory('loginRepository', function ($resource) {
return {
VerifyVisitor: $resource('/api/VisitorWeb/VerifyLogin', {},
{
query: {
method: 'POST',
params: {loginModel: '#loginModel'},
isArray: true }
})
};
});
The parameter variables are enclosed in quotes and prefixed with an #.
I have written a callback method in angularjs. But somehow, it is not called. My code is as follows.
Link function:
link: function(scope, element, attrs) {
scope.getContent = function(itemId) {
getTocService.getArtData(itemId, function(data){
var art = data;
alert(art);
});
}
element.append("<collection collection='member.tocItem'></collection>");
$compile(element.contents())(scope)
}
Service:
app.service(
"getTocService",
function( $http, $q ) {
return({
getArtData: getArtData
});
function getToc(bookIdvar) {
var request = $http({
method: "post",
url: "http://10.132.241.41:8082/apdpoc/services/ApdBookService/getTOC",
params: {
action: "post"
},
data: {
getTOCCriteria:{
bookId: bookIdvar
}
}
});
return( request.then(handleSuccess,handleError));
}
function getArtData(itemId, cb) {
var request = $http({
method: "post",
url: "http://10.132.241.41:8082/apdpoc/services/ApdBookService/getArticle",
params: {
action: "post"
},
data: {
getArticleCriteria:{
articleId: itemId,
locale: "en_US"
}
}
});
return(request.then(handleSuccess,handleError), cb);
}
function handleSuccess(response){
return (response.data);
}
function handleError( response ) {
if (
! angular.isObject(response.data) ||
! response.data.message
) {
return($q.reject("An unknown error occurred."));
}
return($q.reject(response.data.message));
}
}
);
As per my little knowledge on angularJs,
the call back method should execute
var art = data;
alert(art);
these lines. but control is not coming over there. Can someone let me know what is the problem here?
You should update
return(request.then(handleSuccess,handleError), cb);
to
return(request.then(cb,handleError));
I have installed the jsrouting-bundle, and this is my code:
Javascript:
$(document).ready(function () {
$(".pmcontents").hide();
$(".pmbox").click(function () {
$(this).css("font-weight", "normal");
$(this).next().toggle();
var myValue = $('this').attr('id');
var DATA = 'sentValue=' + myValue;
$.ajax({
type: "POST",
url: Routing.generate('isread'),
data: DATA,
cache: false,
success: function (data) {
alert("database has been updated");
}
});
});
});
Controller:
public function isreadAction() {
$request = $this->get('request');
if ($request->isXmlHttpRequest()) {
var_dump($request->request->get('sentValue'));
$em = $this->getDoctrine()->getEntityManager();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBypmid($request->request->get('sentValue'));
$pm->setIsRead(true);
$em->flush();
return new Response();
}
}
Routing:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
_method: POST
I get the following error in my console:µ
Error: The route "isread" does not exist.
So along with the errors that I get on the image below this should be my problem, however I don't know what I have done wrong.
You need to expose the route, like:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
_method: POST
options: # < add these two
expose: true # < lines
» manual