Binding issue in AngularJS - javascript

I am trying to bind from a http get request. The http get is returning true or false. I have tested the get and it is returning properly. When I run the code below, it shows the alert(1111) properly also. However, when I'm trying to change the button text, nothing appears! I have tried everything that I know to do. Any advice would be helpful.
Post.js
myApp.controller('FollowController', ['$scope', '$http', function($scope, $http) {
var status = "";
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
$scope.statusMessage = data;
} else {
//Following - show Follow
$scope.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}]);
Html
<span style="float: right" ng-controller="FollowController as follow">
<button type=" button" class="btn btn-success" onclick="location.href='#Url.Action("Follow", "Home", new { idToFollow = ViewBag.ProfileId, followerId = User.Identity.GetUserId() })'">
{{ follow.statusMessage }}</button>
</span>

You should bind the variables to this instead of $scope as you are using controllerAs approach
Controller
myApp.controller('FollowController', ['$scope', '$http',
function($scope, $http) {
var status = "";
var follow = this;
$http.get('/Home/CheckFollower?idToFollow=' + profileId + '&followerId=' + currentUserId).
success(function(data) {
//check if it is a follower
if (data) {
// Not following - Show unfollow
alert("1111");
follow.statusMessage = data;
} else {
//Following - show Follow
follow.statusMessage = data;
}
})
.error(function(data, status) {
console.log(data);
});
}
]);

Related

AngularJS - Add function

I am just getting started with AngularJS. I'm coming from backend development, so this JavaScript is confusing for me. I followed the AngularJS tutorial and got the basics working.
I have a "record-list.component.js" file (Name derived from the AngularJS demo) which has a function to download data:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
})
This all works fine. However, I want to add another function that will call a URL so the backend can perform some magic. So I tried something like this:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://blackvue.tozz.nl/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
}
function DownloadFileController($file) {
$window.alert("Hi: " + $file);
}
})
This does not work. I tried a variety, such as controller: function, but nothing seems to work. Can someone point me into the good direction?
#Luiz Carlos his answer was correct! I got it working with the following code:
angular.module('recordList').component('recordList', {
templateUrl: 'record-list/record-list.template.html',
controller: function RecordListController($http) {
var self = this;
// self.orderProp = 'age';
$http.get('http://X/camera/record/1/').then(function(response) {
self.recordings = response.data;
});
this.DownloadFileController = function ($file) {
window.alert("Hi!");
}
}
})
And in HTML I can do:
<button ng-click="$ctrl.DownloadFileController()">Test</button>
Thanks!

AngularJs two way data binding doesn't work when add SignalR lib

My problem started when I tried to add a library SignalR in my AngularJs project. I do not know why but the data flow has stopped working properly, I mean that when I try to insert an object into an array I do not see it, but when I try to add another one I see first object, and when I try to add a third object I see only the second.
edit : all code in the angular controller.
app.controller('HomeCtrl', ['$scope', 'HttpSrv', '$state', function ($scope, HttpSrv, $state) {
$scope.messages = [];
activate();
function activate() {
if (HttpSrv.CheckToken()) {
loadPage();
}
};
$scope.$on("$destroy", function () {
con.stop();
});
function connectToChat() {
HttpSrv.http('GET', 'home/GetChatToken').then(function (res) {
localStorage.setItem('ChatToken', res.Result);
con.start({ jsonp: true }, function () { console.log('Start'); });
});
}
var con = $.hubConnection("http://localhost:4704/");
var hub = con.createHubProxy('ChatHub');
hub.on('fail', function (res) {
console.error(res);
});
hub.on('addMessage', addMessage);
$scope.trySend = function () {
hub.invoke('SendMessage', localStorage.getItem('ChatToken'), document.getElementById('messageBox').value);
};
function addMessage(name, message, elementId) {
var tempMessage = '<li id="' + elementId + '" class="right clearfix"><div class="chat-body clearfix">'
tempMessage += '<div class="header"><strong class="pull-left primary-font">' + name + ': </strong> <br />'
tempMessage += '</div><p>' + message + '</p></div></li>'
document.getElementById('chatBody').innerHTML += tempMessage;
document.getElementById('messageBox').value = '';
document.getElementById(elementId).scrollIntoView();
document.getElementById('chatBody').focus();
}
function loadPage() {
HttpSrv.http('GET', 'home/get').then(function (res) {
//console.log(res);
if (res.Status == 200 && res.Succeeded) {
connectToChat();
for (var i = 0; i < res.ListResult.length; i++) {
res.ListResult[i].CreateDate = res.ListResult[i].CreateDate.replace('T', ' ').slice(0, 19);
}
$scope.newsList = res.ListResult;
}
});
};}]);
(i use document.getElementById because of the problem)
First, you shouldn't be building markup in your code. Simply add the message to the list and use ng-repeat in your markup.
However, you also must make sure you use $scope.$apply() or $scope.$digest() when you are processing messages from signalR.
function addMessage(name, message, elementId) {
$scope.$apply(function(){
$scope.messages.push(message);
});
}

Importing Google contacts with angularjs

I'am trying to import a user's gmail contacts using Angular Js. The code is working fine in plain javascript but giving error in angular js.
HTML Code..
<a class="btn btn-primary btn-simple" ng-click="importgoogle()"><u>Import Gmail Friends</u></a>
Angular Code..
var clientId = 'Client ID';
var scopes = 'https://www.googleapis.com/auth/contacts.readonly';
$scope.importgoogle = function(){
window.setTimeout(authorize); //calls authorize()
}
var authorize = function(){
gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization); //calls handleAuthorization()
}
var handleAuthorization = function(){
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
console.log(response);
});
}
}
After entering a user's Id & password the following error message is displayed in console..
Uncaught ReferenceError: authorizationResult is not defined
Can't understand where I'm going wrong as this code is working in Javascript.Please help..
Here is the working example using Angular Js:
app.controller("importGCCtrl", function($scope, $http) {
$scope.config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
$scope.inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
$scope.fetch(gapi.auth.getToken());
});
}
$scope.fetch = function(token) {
$http.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json").then(function(response) {
console.log(response);
//console.log(response.data.feed.entry);
//$scope.contacts = response.data.feed.entry; // to assign data
});
}
});
*NOTE: Please make sure you have included the API - <script src="https://apis.google.com/js/client.js"></script> on the page
The problem lies in the handleAuthorization function. The correct way of implementing that function is..
var handleAuthorization = function(authorizationResult){ //authorizationResult needs to be passed as an arguement.
if (authorizationResult && !authorizationResult.error) {
$.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=500&v=3.0",
function(response){
console.log(response);
});
}
}
After making this change the Angular Js code is now working properly.

Argument 'myCtrl' is not a function, got undefined

I can't seem to solve this issue. I have other controllers done in the same way that work fine but this one gives an error
Error: ng:areq Bad Argument" "Argument 'myCtrl' is not a function, got undefined. Here is my code:
//js
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);
myApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
(function(){
var myContacts = angular.module('myApp');
myContacts.controller('myCtrl', function ($scope, $http) {
$scope.totalContacts = 0;
$scope.request_limit = 3; // this should match however many results your API puts on one page
$scope.pagination = {
current: 1
};
getContacts(1);
// Page changed
$scope.pageChanged = function(newPage) {
getContacts(newPage);
};
// Get function
$scope.getContacts = function(pageNumber){
api_url = '/api/people/list?page=' + pageNumber;
$http.get(api_url).success(function(data){
// Update the scope data
$scope.contacts = data.data;
$scope.totalContacts = data.count
console.log('Data: '+ $scope.contacts);
// Prepare message output
if(data.code == 9999) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 8888) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 1001) {
// No data
// Show info
displayMessage('Info', data.msg);
} else if (data.code == 1000) {
// OK, update the scope
$scope.contacts = data.data;
hideMessage();
}
});
}
});
})();
// html
<html lang="en" ng-app="myApp">
<head>...
<div data-ng-controller="myCtrl" class="container-fluid" id="pcont">
<table class="table no-border hover">
<thead class="no-border">
<tr>
<th class="text-center"><strong>Position</strong></th>
<th class="text-center"><strong>Organization</strong></th>
</tr>
</thead>
<tbody class="no-border-y">
<tr dir-paginate="contact in contacts | itemsPerPage: request_limit" total-items="totalContacts" current-page="pagination.current">
<td class="text-center"><# contact.contact_position #></td>
<td class="text-center"><# contact.organization_name #></td>
</tr>
</tbody>
</table>
What have I done wrong there?
This line in your controller function probably throws an error, because such a function is not defined:
getContacts(1);
Because of this, the controller is not correctly defined so you get the error that you received by angular.
Try removing that line and instead putting this at the end of your controller function:
$scope.getContacts(1);
As a side note, you have the same mistake in the $scope.pageChanged function.
There you should replace getContacts by $scope.getContacts as well.
Still not getting, why you enclosed the controller in a function(), try this:
//js
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);
myApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
myApp.controller('myCtrl', function ($scope, $http) {
$scope.totalContacts = 0;
$scope.request_limit = 3; // this should match however many results your API puts on one page
$scope.pagination = {
current: 1
};
getContacts(1);
// Page changed
$scope.pageChanged = function(newPage) {
getContacts(newPage);
};
// Get function
$scope.getContacts = function(pageNumber){
api_url = '/api/people/list?page=' + pageNumber;
$http.get(api_url).success(function(data){
// Update the scope data
$scope.contacts = data.data;
$scope.totalContacts = data.count
console.log('Data: '+ $scope.contacts);
// Prepare message output
if(data.code == 9999) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 8888) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 1001) {
// No data
// Show info
displayMessage('Info', data.msg);
} else if (data.code == 1000) {
// OK, update the scope
$scope.contacts = data.data;
hideMessage();
}
});
}
});
// html
<html lang="en" ng-app="myApp">
<head>...
<div data-ng-controller="myCtrl" class="container-fluid" id="pcont">
<table class="table no-border hover">
<thead class="no-border">
<tr>
<th class="text-center"><strong>Position</strong></th>
<th class="text-center"><strong>Organization</strong></th>
</tr>
</thead>
<tbody class="no-border-y">
<tr dir-paginate="contact in contacts | itemsPerPage: request_limit" total-items="totalContacts" current-page="pagination.current">
<td class="text-center"><# contact.contact_position #></td>
<td class="text-center"><# contact.organization_name #></td>
</tr>
</tbody>
</table>
I can't seem to find error in your code as it is quite tough format . I am just giving a try so try it .
(function () {
var myApp = angular.module('myApp', ['ngMaterial', 'angularUtils.directives.dirPagination']);
myApp.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
var myContacts = angular.module('myApp');
myContacts.controller('myCtrl', function ($scope, $http) {
$scope.totalContacts = 0;
$scope.request_limit = 3; // this should match however many results your API puts on one page
$scope.pagination = {
current: 1
};
$scope.getContacts(1);
// Page changed
$scope.pageChanged = function (newPage) {
$scope.getContacts(newPage);
};
// Get function
$scope.getContacts = function (pageNumber) {
api_url = '/api/people/list?page=' + pageNumber;
$http.get(api_url).success(function (data) {
// Update the scope data
$scope.contacts = data.data;
$scope.totalContacts = data.count
console.log('Data: ' + $scope.contacts);
// Prepare message output
if (data.code == 9999) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 8888) {
// Show error
displayMessage('Error', data.msg);
} else if (data.code == 1001) {
// No data
// Show info
displayMessage('Info', data.msg);
} else if (data.code == 1000) {
// OK, update the scope
$scope.contacts = data.data;
hideMessage();
}
});
}
});
})();// JavaScript source code
Your definition of controller is kinda weird.
Its kinda weird because your controller is not bootstrap with your application.
You can implement controller in these ways :
Method:1
var myApp = angular.module('myApp', ['ngMaterial','angularUtils.directives.dirPagination']);
myApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('<#');
$interpolateProvider.endSymbol('#>');
});
myApp.controller('myCtrl', function ($scope, $http) {
// .. Rest of the controller code
Take a look in this guide :
Angular controller guide
Method: 2.
var myApp = angular.module('myApp',['ngMaterial','angularUtils.directives.dirPagination'])
.controller('myCtrl', myCtrl)
function myCtrl($location, common , config) {
}
Please check John papa angular convention here
John Papa Convention

Scope are not updated AngularJS

I'm sad... I cook porridge of the ax..
Please, if you can - help me deal with my problem.
I have this structure in my html code(ng-controller is on wrap tag):
<a ng-repeat="subitem in cur_submenu" ng-href="#/{{subitem.href}}/">{{subitem.name}}</a>
In JS I have:
1) RouteProvider
$routeProvider.
when('/:lvl1', {
template:'<div ng-include="htmlUrl">Loading...</div>',
controller: 'MainCtrl'
})
2) Controller
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
MainCtrl.prototype.fetchData();
}
MainCtrl.prototype = {
fetchData: function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
}
}
But it is not updating on my page, when I changed my location on a website(hash-nav)... Please help my. Full version of my site: http://amiu.ru
You don't need to add a function to your Controller with prototyping. Functions called in your view are to be declared on the $scope like so:
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
$scope.fetchData();
}
$scope.fetchData = function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
};
}
In all other cases, if you're executing changes on a $scope outside of a $scope function, you'll need to manually call $scope.$apply() to queue a digest and update your view.

Categories