I am using this directive to show 'loading' division on $http service request.
var module = angular.module('my-app', ['onsen', 'ngAnimate', 'ngMessages']);
module.directive('loading', ['$http', function ($http) {
return {
restrict: 'AE',
link: function ($scope, element, attrs, ctrl) {
$scope.isLoading = function () {
return ($http.pendingRequests.length > 0);
};
$scope.$watch($scope.isLoading, function (v) {
if (v) {
element.removeClass('ng-hide');
} else {
element.addClass('ng-hide');
}
});
}
};
<body ng-controller="BodyController">
<div loading class="spinner-container">
<img src="images/loading.svg" class="spinner" />
</div>
</body>
Want to disable it if this particular function is executing.
module.controller('BodyController', function ($scope, $http, $interval) {
$scope.getNotificationCount = function () {
var url="http://stackoverflow.com" // any url, stackoverflow is an example
var query = "";
$http({
method: 'POST',
url: url,
data: query,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).
success(function (data) {
console.log("success");
}).error(function (data) {
console.log("error");
});
};
$interval($scope.getNotificationCount,30000);
});
I want this because I am calling getNotificationCount() function in $interval() and I don't want to display this my custom loading html div on screen again n again.
Is there any way to achieve this? Help me.
module.directive('loading', ['$http', function ($http) {
return {
restrict: 'AE',
scope : {
isDisabled : '=' // Added new attribute to disable and enable the directive
},
link: function ($scope, element, attrs, ctrl) {
$scope.isLoading = function () {
return ($http.pendingRequests.length > 0);
};
$scope.$watch($scope.isLoading, function (v) {
if(!scope.isDisabled){
// Do things only when isDisabled property is false
if (v) {
element.removeClass('ng-hide');
} else {
element.addClass('ng-hide');
}
}
});
}
};
And your html code should be,
<body ng-controller="BodyController">
<div loading is-disabled="isLoaderDisabled" class="spinner-container">
<img src="images/loading.svg" class="spinner" />
</div>
</body>
Here, isLoaderDisabled is a scope variable. Now you can disable and enable your directive by just set true or false to your scope variable $scope.isLoaderDisabled.
$scope.isLoaderDisabled = false; // Initialize
module.controller('BodyController', function ($scope, $http, $interval) {
$scope.isLoaderDisabled = true; // disable your loading directive
$scope.getNotificationCount = function () {
var url="http://stackoverflow.com" // any url, stackoverflow is an example
var query = "";
$http({
method: 'POST',
url: url,
data: query,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).
success(function (data) {
console.log("success");
}).error(function (data) {
console.log("error");
$scope.isLoaderDisabled = false; // enable your directive
});
};
$interval($scope.getNotificationCount,30000);
});
You should enable your directive on each success function.
Related
I have been trying all and nothing. I wanted create simple circle slider from values with my service, but $scope.value didn't update my view. Take a look at my demo:
https://jsfiddle.net/gh42tqxs/11/
<div ng-app="mainApp">
<div ng-controller="FooController">
<ui-knob value="value" options="options" knob-format data-note="{{note}}"></ui-knob>
</div>
</div>
var app = angular.module("mainApp",['ui.knob']);
app.service('Service', function ($http, $q) {
this.Get = function (premiereId) {
var deferred = $q.defer();
var req = {
method: 'GET',
url: 'https://api.myjson.com/bins/63xhr',
headers: {
'Content-Type': 'application/json'
}
}
$http(req).then(function (response) {
if (response.status == 200) {
deferred.resolve(response.data);
}
else {
deferred.reject(response.data);
}
}, function (error) {
deferred.reject(error.data);
});
return deferred.promise;
}
})
app.controller("FooController", function (Service, $timeout, $scope) {
function test() {
Service.Get().then(function (response) {
$timeout(function () {
console.log(response);
$scope.value = response.Number;
$scope.options.min = response.NumberMin;
$scope.options.max = response.NumberMax;
}, 1000);
})
}
test();
});
Animation isn't starting, we start with the minimum value, not from $scope.value.
ng knob == jquery knob slider
How fix it? Please help me.
/TypeError: Cannot read property 'getToken' of undefined/
I am trying to call getToken function which is defined in the factory function.
Both directive and factories are in separate .js file
but it is throwing an error and is not able to access the function.
angular.module('pesaveWeb')
.directive('goals', function goalsDrctv ($timeout) {
'use strict';
return {
restrict: 'E',
replace: true,
scope: true,
templateUrl: "js/directives/goals.tmpl.html",
controllerAs: 'savings',
controller: function ($routeParams, $scope,
savingsFactory,tokenFactory) {
this.message = {};
var token=tokenFactory.getToken();
var getGoals = savingsFactory.getGoals(token);
if (getGoals) {
getGoals.then( angular.bind(this, function (response) {
savingsFactory.message = response;
this.message = savingsFactory.message;
alert(JSON.stringify(this.message));
}) );
}
}
}
});
angular.module('pesaveWeb').factory('tokenFactory', function tokenFactory ($http,$routeParams) {
'use strict';
var obj = {};
obj.getToken = function () {
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function (data) {
})
.error(function (data) {
});
};
});
Your factory function needs to return the obj you are using to bind the function to.
angular.module('pesaveWeb').factory('tokenFactory', function tokenFactory ($http,$routeParams) {
'use strict';
var obj = {};
obj.getToken = function () {
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function (data) {
})
.error(function (data) {
});
};
return obj;
});
Also, another potential problem is the getToken() function might not work as expected. You should use a "promise" for resolving the value of token in your getToken() function using Angular's $q service. Check out its documentation here
i created this site using django rest framework so that it works without refreshing the page at all,
http://192.241.153.25:8000/#/post/image3
and using angular js's route function was great choice of building a single page app.
but for some reason, the comment box doesn't seem to work possibly because it is put inside the angular js's template.
it throws me csrf token missing error even though the token is included.
judging by the fact that {% csrf token %} tag is visible as a text makes me think that the angular template cannot read the django tag.
could anyone tell me why the comment form isn't functioning and how i can fix this?
(function() {
angular.module('app', ['ngRoute', 'ngResource'])
.controller('FilesListCtrl', ['$scope','$http', function($scope, $http) {//this one controller is new
angular.forEach($scope.posts, function(_post){
$scope.styles = producePostStyle(_post)
});
function producePostStyle(post) {
return { "background-image": "url(" + post.image + ")" }
}
$scope.producePostStyle = producePostStyle;
$http.get('/api/posts/').then(function (response) {
$scope.viewStyle = {
background: 'url('+response.data.results.image+')'
};
});
$scope.images = [];
$scope.next_page = null;
var in_progress = true;
$scope.loadImages = function() {
//alert(in_progress);
if (in_progress){
var url = '/api/posts/';//api url
if ($scope.next_page) {
url = $scope.next_page;
}
$http.get(url).success(function(data) {
$scope.posts = $scope.posts.concat(data.results);//according to api
$scope.next_page = data.next;//acccording to api
if ( ( $scope.next_page == null ) || (!$scope.next_page) ) {
in_progress = false;
}
});
}
};
$scope.loadImages();
}])
angular.module('app')
.controller('profile_image', ['$scope','$http', function($scope, $http) {//this one controller is new
$http({
url: '/api/users/profile/',
method: "GET",
params: {username: 'lifeto'}
}).then(function successCallback(response) {
console.log("Profile Image");
console.log(response);
$scope.lifeto_img = response.data;
}, function errorCallback(response) {
console.log("Error fetching profile image!");
});
}])
.directive('whenScrolled', function($document) {//another directive
return function(scope, elm, attr) {
var raw = elm[0];
$document.bind('scroll', function() {
if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
scope.$apply(attr.whenScrolled);
}
});
};
})
.config(function($resourceProvider, $routeProvider, $httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
// Don't strip trailing slashes from calculated URLs
$resourceProvider.defaults.stripTrailingSlashes = false;
$routeProvider
.when('/', {
template: '<posts></posts>'
})
.when('/posts', {
template: '<posts></posts>'
})
.when('/post/:postId', {
template: '<post></post>'
})
.otherwise({
redirectTo: '/'
});
});
angular.module('app')
.constant('API_URL', '/api/posts/');
angular.module('app')
.factory('Posts', function($resource, API_URL) {
return $resource(API_URL, {format: 'json'}, {
queryPosts: {
method: 'GET',
isArray: false
},
getPostInfo: {
url: API_URL + ':postId/',
method: 'GET',
isArray: false,
params: {
postId: '#postId',
format: 'json'
}
}
});
});
angular.module('app')
.directive('post', function() {
return {
restrict: 'E',
templateUrl: '/static/post.html',
scope: {},
controller: function($scope, $routeParams, Posts) {
$scope.post = null;
function clean(id) {
return id.toLowerCase().replace(/\s/g, "-");
}
function _initialize() {
Posts.getPostInfo({
postId: clean($routeParams.postId)
})
.$promise
.then(function(result) {
$scope.post = result;
console.log(result)
});
}
_initialize();
}
};
});
angular.module('app')
.directive('posts', function() {
return {
restrict: 'E',
templateUrl: '/static/posts.html',
scope: {},
controller: function($scope, Posts) {
$scope.posts = [];
function _initialize() {
Posts.queryPosts().$promise.then(function(result) {
$scope.posts = result.results;
});
}
_initialize();
}
};
});
})();
Since you added
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
$http will take care of csrf.
Now you can post data using $http
$http({
method: 'POST',
url: '/url/',
data: {
"key1": 'value1',
},
}).then(function successCallback(response) {
#do
},
function errorCallback(response) {
#do
});
Note: Dont use Ajax Post here. For that you have to do some csrf things other than this.
I am switching to a Angular-ui modal and I am confused on how to make a $http get call and return the results. I have been using a different angular modal with the current code. I understand ow this is working but I need some help on the transition. thanks
This is the modal I am currently using. this works fine. I need to apply this to the Angular-UI modal
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
$scope.openEditCivilCaseModal = $ekathuwa.modal({
scope: $scope,
contentPreSize: "lg",
templateURL: "views/modals/editCivilCaseModal.html"
});
//show modal window
$scope.openEditCivilCaseModal.then(function (m) {
m.modal('show');
});
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
need to switch to this
.controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ["item1", "item2", "item3"];
$scope.open = function (id) {
var modalInstance = $modal.open({
templateUrl: "views/modals/editCivilCaseModal.html",
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then((function (selectedItem) {
$scope.selected = selectedItem;
}), function () {
$log.info("Modal dismissed at: " + new Date());
});
};
}
).controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
}
Solution per the suggested solution
//Edit Civil Modal
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
}).error(function (error) {
deferred.reject(error);
}).then(function () {
$modal.open({
templateUrl: "views/modals/editCivilCaseModal.html",
controller: 'ModalInstanceCtrl',
resolve: {
active: function () {
return $scope.active;
}
}
});
})
return deferred.promise;
}
.controller('ModalInstanceCtrl', function ($scope, $modalInstance, active) {
$scope.active = active
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss("cancel");
};
});
you should split your $http call
$scope.editCivilCaseModal = function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: '/api/apiCivilCase/' + id })
.success(function (civilCase) {
deferred.resolve(civilCase);
console.log(civilCase);
$scope.active = civilCase;
}).error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
and on success of http do whatever you like opening the model.
$scope.editCivilCaseModel().then(function(){
$scope.openEditCivilCaseModal = $ekathuwa.modal({
scope: $scope,
contentPreSize: "lg",
templateURL: "views/modals/editCivilCaseModal.html"
});
//show modal window
$scope.openEditCivilCaseModal.then(function (m) {
m.modal('show');
});
})
this is just to give you the concept because I am not able to see the exact relationship between now and expected.
I can't understand where is the problem.
I trying to display my form only when image is loaded, all works fine, except such annoying thing. When I'm trying to set $scope.show_image = true; without line $timeout(function(){}, 0); before, my form not appears.
<script type="text/javascript">
'use strict';
var app = angular.module('albumgallery', []);
app.factory('Photo', ['$http', '$rootScope', function($http, $rootScope) {
var photo;
function getPhoto() {
$http({method: 'GET', url: 'photoInfo'})
.success(function(data, status, headers, config) {
photo = data;
$rootScope.$broadcast('photo:loaded');
})
.error(function(data, status, headers, config) {
console.log(data);
});
}
getPhoto();
var service = {};
service.get = function() {
return photo;
}
return service;
}]);
function PhotoInfoCtrl($scope, $rootScope, $timeout, Photo) {
$rootScope.$on('photo:loaded', function() {
$scope.photo = Photo.get();
});
// -------------- MY PROBLEM --------------------
$rootScope.$on('image:loaded', function() {
$timeout(function(){}, 0);
$scope.show_image = true;
});
};
app.directive('imageonload', function factory($rootScope) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
$rootScope.$broadcast('image:loaded');
});
}
}
});
</script>
When I set timeout my form shows perfectly, but when i write only
$rootScope.$on('image:loaded', function() {
$scope.show_image = true;
});
something goes wrong and form not displayed. Please help understand my mistake.