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.
Related
I am calling a json in controller using service but I am receiving an error saying "TypeError: Cannot read property 'then' of undefined". I tried existing answers but couldn't get it to work.
Controller:
app.controller("myController",["$scope","MyService","$http", function($scope,MyService,$http){
$scope.hi = "hello";
MyService.getMyData().then(function(response){
console.log(response);
});
}]);
Service:
app.service("MyService", ["$http", function($http) {
this.getMyData = function() {
return
$http({
method: 'GET',
url: 'myList.json',
headers: {
'Content-Type': 'application/json'
}
}).then(function successCallback(response) {
console.log(response);
return response;
}, function errorCallback(response) {
console.log(error);
return response;
});
};
}]);
Thank you.
Currently you had just return(on first line) thereafter on next line you returned $http promise. Basically you have return alone it returns nothing/undefined (this is how javascript works) & next statements are getting ignored from this.getMyData function.
You have to have return & $http({ promise to be together in one line, otherwise return will return empty statement.
this.getMyData = function() {
//`return` & `$http` promise should be on same line, otherwise undefined would get return
return $http({
method: 'GET',
url: 'myList.json',
headers: {
'Content-Type': 'application/json'
}
}).then(function successCallback(response) {
console.log(response);
return response;
}, function errorCallback(response) {
console.log(error);
return response;
});
};
#pankajparker is absolutely correct.
Implemented a codepen for kicks and adjusted to use Angular 1.5's components. Here's the link:
http://codepen.io/Lethargicgeek/pen/YWryoE
(function() {
angular.module("myApp", []);
angular.module("myApp").component('myCmp', {
controller: ctrlFn,
templateUrl: "myCmp.tpl.html"
});
ctrlFn.$inject = ["myService"];
function ctrlFn(myService) {
var $ctrl = this;
// BINDINGS
$ctrl.hi = "hello";
$ctrl.getData = getData;
$ctrl.data = null;
$ctrl.myService = myService; // Binding so that we can easily see results
// END BINDINGS
// FUNCTION
function getData() {
var returnedPrms = myService.getMyData();
returnedPrms.then(function(response) {
$ctrl.data = response;
});
}
// END FUNCTIONS
}
angular.module("myApp").service("myService", svcFn);
svcFn.$inject = ["$http"];
function svcFn($http) {
var svc = this;
//BINDINGS
svc.getMyData = getMyData;
//END BINDINGS
function getMyData() {
var firstPrms = $http.get("http://codepen.io/anon/pen/LVEwdw.js"); // Random bit of json pulled from internets
var secondPrms = firstPrms.then(function success(response) {
svc.successResp = response;
return response;
}, function error(response) {
svc.errorResp = response;
return response;
});
return secondPrms;
}
}
})(); // end iife
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script>
<div ng-app="myApp">
<script type="text/ng-template" id="myCmp.tpl.html">
<div>
<h1>{{$ctrl.hi}}</h1>
<a class="btn btn-primary" ng-click="$ctrl.getData()">
Trigger $Http Call
</a>
<dl class="dl-horizontal">
<dt>$ctrl.data:</dt>
<dd>{{$ctrl.data}}</dd>
<dt>$ctrl.myService.successResp:</dt>
<dd>{{$ctrl.myService.successResp}}</dd>
<dt>ctrl.myService.errorResp:</dt>
<dd>{{ctrl.myService.errorResp}}</dd>
</dl>
</div>
</script>
<my-cmp></my-cmp>
</div>
I offloaded the call to the Twitter API from my controller into a service:
angular.module('main')
.service('Tweet', function ($log, $http, Config, $ionicLoading) {
this.show = function () {
$ionicLoading.show({
template: '<ion-spinner></ion-spinner><br>Loading'
}).then(function () {
$log.log("The loading indicator is now displayed");
});
};
this.hide = function () {
$ionicLoading.hide().then(function () {
$log.log("The loading indicator is now hidden");
});
};
var consumerKey = encodeURIComponent(Config.TWITTER.CONSUMERKEY);
var consumerSecret = encodeURIComponent(Config.TWITTER.CONSUMERSECRET);
var tokenCredentials = btoa(consumerKey + ':' + consumerSecret);
this.getToken = function () {
this.show();
return $http({
method: 'POST',
url: 'https://api.twitter.com/oauth2/token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + tokenCredentials
},
data: 'grant_type=client_credentials'
})
.then(function (result) {
if (result.data && result.data.access_token) {
$http.defaults.headers.common.Authorization = 'Bearer ' + result.data.access_token;
}
})
.catch(function (error) {
console.log(error);
});
};
this.getTimeline = function () {
$log.log($http.defaults.headers.common.Authorization);
return $http({
method: 'GET',
url: 'https://api.twitter.com/1.1/search/tweets.json?q=%40postbank',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
})
.then(function (result) {
return result.data.statuses;
})
.catch(function (error) {
console.log(error);
});
};
this.analyzeResult = function (input) {
this.tweets = input;
this.hide();
};
var that = this;
this.getTweets = function () {
this.getToken()
.then(this.getTimeline)
.then(function (result) {
that.analyzeResult(result);
});
}
});
I inject the service into my main controller and call the getTweets() function:
angular.module('main')
.controller('MainCtrl', function ($log, Tweet) {
Tweet.getTweets();
});
I can see that all the promises are executed through the console, but this.tweets stays empty. How do I send the data that is coming from the service/promise to the controller?
this within service constructor is service's context, not controller's. And services shouldn't operate on the scope.
Unwrap service promise in controller:
var self = this;
Tweet.getTweets().then(function () {
self.tweets = input;
});
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.
I've ProductService and ProductsController. ProductService have ProductService.Products = []; variable which contains all the Products information.
I access this Products-information in ProductsController and stores in variable named $scope.Products = [];.
Problem is some other service also using "ProductService", and updating "Products Info", using "UpdateInfo" function exposed in ProductService. Now these changes are not getting reflected in ProductsController variable $scope.Products = [];.
This is my code.
sampleApp.factory('ProductService', ['$http', '$q', function ($http, $q){
var req = {
method: 'POST',
url: 'ProductData.txt',
//url: 'http://localhost/cgi-bin/superCategory.pl',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }//,
//data: { action: 'GET' }
};
var ProductService = {};
ProductService.Products = [];
return {
GetProducts: function () {
var defer = $q.defer();
$http(req).then(function(response) {
ProductService.Products = response.data;
defer.resolve(ProductService.Products);
}, function(error) {
defer.reject("Some error");
});
return defer.promise;
},
UpdateInfo: function (ProductID, VariantID) {
for (i in ProductService.Products) {
if (ProductService.Products[i].ProductID == ProductID) {
for (j in ProductService.Products[i].Variants) {
if (ProductService.Products[i].Variants[j].VariantID == VariantID) {
ProductService.Products[i].Variants[j].InCart = 1; /* Updating Info Here, But its not reflecting */
break;
}
}
break;
}
}
}
};
}]);
sampleApp.controller('ProductsController', function ($scope, $routeParams, ProductService, ShoppingCartService) {
$scope.Products = [];
$scope.GetProducts = function() {
ProductService.GetProducts().then
(
function(response) {
$scope.Products = response;
},
function(error) {
alert ('error worng');
}
);
};
$scope.GetProducts();
});
Can some one help me how to solve this issue?
You can create a $watch on ProductService.Products in your controller. When the value changes, you can update $scope.Products with the new value.
$scope.$watch('ProductService.Products', function() {
$scope.Products = ProductService.Products;
});
Try assigning ProductsService.Products to $scope.products.
$scope.GetProducts = function() {
ProductService.GetProducts().then
(
function(response) {
$scope.Products = ProductService.Products;
},
function(error) {
alert ('error worng');
}
);
};
I have following controller which is posting a new user and also getting new users.
The problem here is after adding a new user, the scope is not updated so view is not affected. I have also tired returning the function so it expects a promise but didnt update the scope.
myapp.controllers('users', ['usersService', ''$scope',', function(usersService, $scope){
getUsers();
function getUsers(params) {
if (typeof(params) === "undefined") {
params = {page: 1};
}
usersService.getUsers(params).then(function (res) {
$scope.users = res.items;
$scope.usersListTotalItems = res._meta.totalCount;
$scope.usersListCurrentPage = res._meta.currentPage + 1;
});
}
}
$scope.addUser = function (user) {
usersService.adddNewUser(user).then(function (response) {
getUsers();
});
}
}]);
myApp.factory('userService', ['Restangular', '$http', function (Restangular, $http) {
return {
getUsers: function (params) {
var resource = 'users/';
var users = Restangular.all(resource);
return users.getList(params)
.then(function (response) {
return {
items : response.data[0].items,
_meta : response.data[0]._meta
}
});
},
adddNewUser: function (items) {
var resource = Restangular.all('users');
var data_encoded = $.param(items);
return resource.post(data_encoded, {}, {'Content-Type': 'application/x-www-form-urlencoded'}).
then(function (response) {
return response;
},
function (response) {
response.err = true;
return response;
});
}
};
}]);
I think it is a small error however you did not include $scope in the argument for the controller function.
myapp.controllers('users', ['usersService','$scope', function(usersService $scope){
getUsers();
function getUsers(params) {
if (typeof(params) === "undefined") {
params = {page: 1};
}
usersService.getUsers(params).then(function (res) {
$scope.users = res.items;
$scope.usersListTotalItems = res._meta.totalCount;
$scope.usersListCurrentPage = res._meta.currentPage + 1;
});
}
}
$scope.addUser = function (user) {
usersService.adddNewUser(user).then(function (response) {
getUsers();
});
}
}]);