AngularJS - Add function - javascript

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!

Related

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.

Caching internationalization JSON data in AngularJS

Here i am created multi-language concept in my application its working fine, but language (.json) file loaded for every field, So application taking time to load, my requirement is i want to load .json only once to fetch all the data , how to do in angularJs, Thanks for your help in advance
please check the below link also
http://plnkr.co/edit/PYZxcI5yTNuA0fEern9s?p=preview
var language = 'en';
app.directive('telBasictext', ['$http', 'teli18nservice',
function($http, teli18nservice) {
return {
restrict: 'AEC',
require: 'ngModel',
scope: {
ngModel: '=',
},
template: '<div class="form-group" > ' +
'<label > {{ setvalue }} </label> ' +
'<div > <input type="{{ textboxtype }}" ng-model="ngModel" ></div></div>',
link: function(scope, iElement, iAttrs, ngModelController) {
var collecton = iAttrs.getString;
var splitValues = collecton.split(",");
var language = splitValues[0]; // Language EN or Fr
var labelName = splitValues[1]; // Label Name
var moduleName = splitValues[2]; // Module Name (global or local)
teli18nservice.getdata(moduleName).success(function(data) {
scope.setvalue = data[labelName];
})
.error(function(error) {
scope.setvalue = "No Label";
});
}
};
}
]);
Store the result of a request for the JSON locally in your teli18nservice service and return that data for subsequent calls to getdata. It would look something like this:
// teli18nservice
var jsonData;
this.getData = function () {
if (jsonData) {
return $q.resolve(jsonData);
}
$http.get().then(function (res) {
jsonData = res.data;
return jsonData;
});
}
Alternatively, take a look at caching $http responses.
May be you should use the cache of $http.
example taken from here:
var cache = $cacheFactory('myCache');
var data = cache.get(someKey);
if (!data) {
$http.get(url).success(function(result) {
data = result;
cache.put(someKey, data);
});
}

Binding issue in AngularJS

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);
});
}
]);

AngularJS Defer.promise not working as expected

I'm developing an application using AngularJS & PersistenceJS.
I'm getting trouble dealing with Asynchronous calls as the
Controller :
cars.controller('CrashWidgetOneCtrl',function($scope, $location, $routeParams, CrashServices){
if($routeParams.crashId){
$scope.data = {};
console.log("CrashID: "+$routeParams.crashId);
crashId = $routeParams.crashId;
alert(1);//Works
CrashServices.getCrashDetails($scope, crashId).then(function(result){
console.log(result);
alert(2);//Never Fires
});
alert(3);//Gets executed
}else{
console.log("N");
}
});
Services :
cars.factory('CrashServices', function($http, $location, $q, CommonServices,$rootScope, $timeout){
return{
getCrashDetails:function($scope, crashId){
var deferred = $q.defer();
// Get user details if any
$scope.$apply(function(){
var crashInfoTable = App.CrashInfoTable.all();
alert(4);
crashInfoTable.list(null, function (results) {
alert(5);//This also doesn't work
deferred.resolve();
});
});
return deferred.promise;
}
}
});
Any help will be greatly appreciated. Many thanks.
Note: I am using PersistenceJS.
I dont know if you need the scope.apply.
This seemed to work for me:
getCrashDetails:function($scope, crashId){
var deferred = $q.defer();
// Get user details if any
App.CrashInfoTable.all().list(null, function(results) {
deferred.resolve(results);
});
return deferred.promise;
}

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