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);
});
}
Related
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!
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);
});
}
Is there a way to access a file from a type="file" input in javascript?
The purpose is to send it with XHR afterwards.
Example :
<input type="file" id="myFile"/>
var file = $('#myFile');
With AngularJS :
<input type="file" file-changed/>
.directive('fileChanged', function(){
return {
link : function(scope, element){
element.on('change', function(e){
if(e.target.value != ""){
scope.myCtrl.file = e.target;
}
});
}
}
)
.controller('myCtrl', function(){
var self = this;
self.file;
//self.file should be available here for XHR.
});
Global need :
Multiple input type files needs to be send to a REST api.
I need to keep track of the progress of each file upload, WITHOUT using an external libary.
This can be accomplished easily through FileReader
This is well supported these days http://caniuse.com/#feat=filereader
Here is a snippet of code from HTMLGoodies that will help you get started ::
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert("Got the file.n" + "name: " + f.name + "n" + "type: " + f.type + "n" + "size: " + f.size + " bytesn" + "starts with: " + contents.substr(1, contents.indexOf("n")));
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
You can use this directive below to attach the file to some $scope variable:
HTML:
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">Upload</button>
DIRECTIVE:
angular.module('yourApp').directive('fileModel', ['$parse', function ($parse) {
"use strict";
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel),
modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
CONTROLLER:
$scope.uploadFile = function () {
var file = $scope.myFile,
uploadUrl = "URL://";
fileUploadService.uploadFileToUrl(file, uploadUrl, function (err, data) {
$scope.ret = err || data;
});
};
Hope this helps.
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);
});
}
]);
I made a directive for automatically add links for a html validation, like that :
.directive('validationhtml', function($rootScope, $location) {
return {
restrict: 'A',
template: 'validation html',
controller: function($scope, $location) {
$scope.getUrl = function() {
var url = 'http://validator.w3.org/check?uri=' + $location.path;
console.log(url);
return url;
}
}
};
})
createTab(); is a function in rootscope, and correctly executed (new tab), but getUrl(); have a problem: the url is not good, in the return i have this
http://validator.w3.org/check?uri=function (c){if(B(c))return this[b];this[b]=a(c);this.$$compose();return this}
what's wrong ?
It should be location.path().
$location path is a function:
var url = 'http://validator.w3.org/check?uri=' + $location.path();