erp.directive("auto1", [ '$http', function( $http) {
var mydata;
var x;
var y;
data = function(){
return $http.get("./php/fetchElement.php").then(function (response) {
mydata = this;
mydata = response.data.records;
});
};
function run(){
return data().then(function(response){
return mydata.map(function(ele){
return ele.Name;
});
});
}
x = run();
console.log(x);
return {
restrict: 'A',
link: function() {
$('#auto1').autocomplete({source:[x]})
}
};
}]);
Please help me! I cannot take the array "ele.Name" out of the function. When inside it is an expected array. But when assign to "x" it is a complicated object that I cannot access for desired value.
Related
I need to inject some piece of code into a function, to prevent DRY. Here is an example of my code.
angular.module('crypt', ['ui.chart'])
.controller('MainCtrl', ['$http', function($http) {
var self = this;
self.encrypt = function() {
$http.post('/encrypt',
{'crypt': {'text': self.plain, 'shift':self.rot}})
.then(function(response) {
self.encrypted = response.data.encrypted;
self.plain = '';
// reusable function goes here
// var frequencyArr = response.data.frequency;
// var frequencyArrLength = frequencyArr.length;
// if (frequencyArrLength) self.cryptChart = [frequencyArr];
});
};
self.decrypt = function() {
$http.post('/decrypt',
{'crypt': {'text': self.encrypted, 'shift':self.rot}})
.then(function(response) {
self.plain = response.data.plain;
self.encrypted = '';
// and here
// the stuff to become a function
var frequencyArr = response.data.frequency;
var frequencyArrLength = frequencyArr.length;
if (frequencyArrLength) self.cryptChart = [frequencyArr];
});
};
// ...
}])
So how do I pack that 3 lines and make a reusable function in Angular way?
Maybe like this:
angular.module('crypt', ['ui.chart'])
.controller('MainCtrl', ['$http', function($http) {
var self = this;
function cryption(decrypt, callBack) {
$http.post(
decrypt ? '/decrypt' : '/encrypt',
{crypt: {text: decrypt ? self.encrypted : self.plain, shift: self.rot }})
.then(callBack);
}
function cryptChart(response) {
var frequencyArr = response.data.frequency;
var frequencyArrLength = frequencyArr.length;
if (frequencyArrLength) // can be simplyfied to response.data.frequency.length
self.cryptChart = [frequencyArr];
}
self.encrypt = cryption(false, function(response) {
self.encrypted = response.data.encrypted;
self.plain = '';
cryptChart(response);
});
self.decrypt = cryption(true, function(response) {
self.plain = response.data.plain;
self.encrypted = '';
cryptChart(response);
});
// ...
}])
I went bit further and extracted the shared $http.post call into function as well.
In the script below i try to access the data from the cartDataService, even though i manage to read this.test from the cartDataService, i get an empty value for the cart_id. I know it is due to the asynchronous characteristics of javascript
i am pretty sure that i try to access the cart_id from the service before it is assigned, how do i make sure that the cart_id from the service is assigned? thank you
var app = angular.module('myApp', [])
app.service('cartDataService', function () {
this.cart_id = ""
this.getcart_id = function(){ return this.cart_id};
this.setcart_id = function(id){
this.cart_id = id
}
this.test = "byebye"
})
app.controller('OrderDetailCtrl', ['$http', 'cartDataService', function ($http, cartDataService) {
var self = this
self.msg = 'Order Detail'
self.order_id = outer_id
self.orders = {
get: function () {
return $http.get('http://apimucommerce/api/order/' + self.order_id + '/')
.then(function (response) {
return response.data
})
}
}
self.orders.get().then(function (data) {
self.order = data
self.cart_id = self.order.cart_id
cartDataService.setcart_id(self.order.cart_id)
})
}])
app.controller('CartController', ['cartDataService', function (cartDataService) {
var self = this
self.cart_id = cartDataService.getcart_id()
alert(cartDataService.cart_id)
self.msg = cartDataService.test
}])
You can use this:
app.controller('CartController', ['$scope', 'cartDataService', function ($scope, cartDataService) {
var self = this
$scope.$watch(
function () watcher{
return cartDataService.getcart_id();
},
function () onCardIdChanged{
self.cart_id = cartDataService.getcart_id()
alert(self.cart_id);
}
);
}]);
Another way to solve your problem:
app.service('cartDataService', ['$q', function ($q) {
var deffered = $q.defer();
this.cart_id = "";
this.getcart_id = function(){
return deffered.promise;
};
this.setcart_id = function(id){
this.cart_id = id;
deffered.resolve(;
}
}]);
app.controller('CartController', ['$scope', 'cartDataService', function ($scope, cartDataService) {
var self = this;
cartDataService.getcart_id().then(function (cardId) {
self.cart_id = cartDataService.getcart_id()
alert(self.cart_id);
});
}]);
UPD:
app.service('cartDataService', ['$q', function ($q) {
var deffered = $q.defer();
this.cart_id = "";
this.getcart_id = function(){
return deffered.promise;
};
this.setcart_id = function(id){
this.cart_id = id;
deffered.resolve(id);
}
}]);
app.controller('CartController', ['$scope', 'cartDataService', function ($scope, cartDataService) {
var self = this;
cartDataService.getcart_id().then(function (cardId) {
self.cart_id = cardId;
alert(self.cart_id);
});
}]);
I cannot seem to set my product variable properly from within my getProduct() function...
If I console.log(product) immediately after angular.copy(products.data[i], product);, it is set there correctly, however I cannot figure out why var product = {}; on line 3 remains an empty object.
Any ideas what is going?
angular.module('APP').factory('productFactory', function($q, $http) {
var products = [];
var product = {};
var getAllProducts = function(){
return $http.get('./data/product.json')
.then(function(response) {
angular.copy(response, products);
var deferred = $q.defer();
deferred.resolve(response);
return deferred.promise;
});
};
var getProduct = function(id) {
getAllProducts()
.then(function(){
for (var i = products.data.length - 1; i >= 0; i--) {
if(products.data[i].id == id){
angular.copy(products.data[i], product);
}
};
})
};
return {
getAllProducts: getAllProducts,
getProduct: getProduct,
products: products,
product: product
};
})
I declare $scope.something in my controller like
app.controller('MainControl', function($scope){
$scope.something = 1;
});
then how can I access it in my filter scope? like
app.filter("myCustomFilter", function () {
// here
});
obviously it doesn't work if I just $scope.something there.
After a chat here is the working solution http://jsbin.com/juxebewu/4/edit
<div ng-controller="sCtr">
<ul>
<li>{{aa | friends:this}}</li></ul>{{showItem}}
<p ng-show="showItem">click</p>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
var app = angular.module('App', []);
var targetOfFriendTasks = 1;
var user = [];
user[0]= {uId: 1};
app.filter("friends", function () {
return function (input, s) {
var output = [];
for (var i in input) {
if (input[i].name.length >= 1 && input[i].uId == targetOfFriendTasks) {
output.push(input[i]);
}
}
if (targetOfFriendTasks != user[0].uId) {
return output;
} else {
s.showItem = true;
}
};
});
app.controller('sCtr', function ($scope) {
$scope.aa = [{name:"lorem", uId:1}, {name:"ipsum", uId:2}];
$scope.showItem = false;
});
Given the following code:
function Ctrl($scope, $http, $q) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5').
success(function(data3) {
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
};
};
$scope.$watch('name', search, true);
var done = $scope.getDetails = function (id) {
$scope.clicked = true;
$scope.sliding = true;
var api = 'http://api.discogs.com/artists/';
return $q.all([$http.get(api + id),
$http.get(api + id + '/releases?page=1&per_page=100')]);
};
done.then(function (){
$scope.releases = data2.releases;
$scope.artist = data;
return $http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json');
});
I'm getting the following console error:
TypeError: Object function (id) {
$scope.clicked = true;
$scope.sliding = true;
var api = 'http://api.discogs.com/artists/';
return $q.all([$http.get(api + id),
$http.get(api + id + '/releases?page=...<omitted>... } has no method 'then'
at new Ctrl (file:///C:/Users/Zuh/Desktop/AngularJS%20Discogs/js/services.js:27:9)
Can anybody point me to where might the error be? I'm defining the .then after getDetails is executed...
Here's a working Plunker.
Here is your updated plunkr http://plnkr.co/edit/lTdnkRB1WfHqPusaJmg2?p=preview
angular.module('myApp', ['ngResource']);
function Ctrl($scope, $http, $q) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=5').
success(function(data3) {
console.log(arguments)
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
};
};
$scope.$watch('name', search, true);
var done = $scope.getDetails = function (id) {
$scope.clicked = true;
$scope.sliding = true;
var api = 'http://api.discogs.com/artists/';
var q = $q.all([$http.get(api + id),
$http.get(api + id + '/releases?page=1&per_page=100')])
.then(function (ret){
//console.log(arguments)
$scope.releases = ret[1].data.releases;
$scope.artist = ret[0];
return $http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + name + '&album='+ title +'&format=json');
})
return q
};
}
To sum up fixes:
move $q.all().then() part into done method
pay more attention to what parameters handlers received in then part.