How to make document ready conditional using AngularJS? - javascript

I'm using ASP.NET MVC and AngularJS as my framework. I've a link which send request to MCV Action and finally gets forwarded to view. This view has registered JavaScript File which loads angular.element(document).ready(function (e){} function. Basically I'm trying to create a if else statement inside angular.element(document).ready. based on myparam=true. How can I do it?
Link -
"<h7>" + "" + "<a target=\"_blank\" href='/Submission/EditSubmissionFile?id=" + SubmissionID + "&myparam=true" +"'>" + "Add Attachment" + "</a><br></h7>" +
AngularJS Javascript File -
mainApp.controller('editSubmissionFileController', ['$scope', '$location', '$http', 'viewDataService', 'utilityService', '$window', 'constants', '$timeout', 'constants', 'adComplianceUtility', 'submissionRuleService',
function ($scope, $location, $http, viewDataService, utilityService, $window, constants, $timeout, constants, adComplianceUtility, submissionRuleService) {
angular.element(document).ready(function (e) {
// How to make this conditional based on parameter passed from Action or html link?
$scope.$broadcast('ShowFileUpload', {
SubmissionID: $scope.model.data.SubmissionID,
Show: true,
Callback: function (data) {
$scope.onFileUploadSuccessful(data);
}
})
});
}
Action -
public ActionResult EditSubmissionFile(int id)
{
// We can only see what we are allowed
UserContext.TestSubmissionExists(id);
UserContext.TestSubmissionAccess(id, AccessRightEnum.ViewSubmissions);
var model = _submissionSvc.GetSubmissionViewModel(id);
return View("EditSubmissionFile", model);
}

Adding a simple window.location.href and check if parameter exists in URL does the job. Sometimes simple is better! Thank you.
angular.element(document).ready(function (e) {
// Check if URL contains a parameter value to restrict default pageload function.
if (window.location.href.indexOf("myparam=true") > -1)
{
$scope.$broadcast('ShowFileUpload', {
SubmissionID: $scope.model.data.SubmissionID,
Show: true,
Callback: function (data) {
$scope.onFileUploadSuccessful(data);
}
})
}
});

Related

AngularJS code hangs browser

I am calling a Web Service which returns around 3000 records as data entries as HTML response & i am trying to read this response using angularJS.
Below is my AngularJS code i am using to call the service
angular.module('tabApp', ['ngSanitize'])
.controller('TabController', ['$scope', 'HttpService', function($scope, HttpService) {
$scope.tab = 0;
$scope.setTab = function(newTab){
$scope.tab = newTab;
$scope.loading = true;
HttpService.CallService('Service.php?id='+newTab,newTab, function (data) {
$scope.myText = data;
$('.count').show();
$("[id^=searchg]").show();
$('.results').show();
});
};
$scope.isSet = function(tabNum){
return $scope.tab === tabNum;
};
$scope.setTab1 = function(newTab1){
$scope.tab = newTab1;
$('.loaderImage').hide();
};
$scope.isSet1 = function(tabNum){
return $scope.tab === tabNum;
};
}])
.service('HttpService', ['$rootScope', '$http', function ($rootScope, $http) {
$rootScope.loading = true;
return {
CallService: function (url,tabnum, callback) {
$http({
method: "POST",
url: url,
data: {id: tabnum}})
.success(function (data, status) {
$('.loaderImage').hide();
callback(data, status);
}).error(function (data, status) {
$('.loaderImage').hide();
callback(status);
});
}
}
}]);
My problem is the browser hangs if the returned records are more than 1500. Please advise on how i can improve this.
Update:
My html code looks like this
<div ng-show="isSet(1)">
<div id=matches style="display:none"></div>
<input type=text id=searchg placeholder="Type to search..." style="display:none" />
<p class="preload" ng-bind-html="myText"></p>
</div>
As we can see it is the bulky data which you are trying to bind. In Future, it could be more bulky.
You should use the server side pagination and get only the number of records, what your pagination is.
Here is the JSFiddle link for the reference.
http://jsfiddle.net/dwahlin/3Kewg/
Hope this helps! CHEERS TO CODE! :)
As #Mohit Dixit suggested, you should prefer to do server side paging and request only active page records.
I would advise you to use smart table library for this. Here is the official website for same. They support paging(both server side and client side), filter and sorting in one go.
Please note that there are many library available for this purpose but I am suggesting this as I am using it from past few years.

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.

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

construct url in angularjs directive

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();

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