I have this code in my Angular controller:
app.controller('CompaniesView', ['$scope', '$http', '$location', '$routeParams', '$route', 'noty', function($scope, $http, $location, $routeParams, $route, $noty) {
var id = "";
if ($routeParams.id !== undefined) {
id = '/' + $routeParams.id;
}
$http.get(Routing.generate('company-info') + id).success(function(data) {
if (data.message) {
$noty.error(data.message);
} else {
$scope.company = data.company;
$scope.status = data.status;
$scope.updStatus = $scope.company.status;
$scope.orderProp = 'name';
}
}).error(function(data, status, headers, config) {
if (status == '500') {
$noty.error("No hay conexión con el servidor");
}
});
$scope.$watch("updStatus", function() {
$http.post(Routing.generate('updateCompanyStatus'), {
'newStatus': $scope.updStatus
}).success(function(data) {
if (data.message) {
$noty.error(data.message);
}
}).error(function(data, status, headers, config) {
if (status == '500') {
$noty.error("No hay conexión con el servidor");
}
});
});
}]);
Any time I load the page the updStatus is called twice, so how I prevent the $watch to be executed and just call the function when the ng-model="updStates" changes? I have the same behavior with other controllers, I miss something at $watch docs? It's not supposed that this will only works if ng-model changes?
If you're using an ng-model it's usually easier to use the ng-change directive instead of $watch:
<input ng-model="foo" ng-change="fooChanged()"/>
Every time foo changes your fooChanged() function will be called.
Usually you put a check inside of the watch comparing previous an current value:
$scope.$watch("updStatus", function(newVal, oldVal) {
if (newVal != oldVal) {
$http.post(Routing.generate('updateCompanyStatus'), {
'newStatus': $scope.updStatus
}).success(function (data) {
if (data.message) {
$noty.error(data.message);
}
}).error(function (data, status, headers, config) {
if (status == '500') {
$noty.error("No hay conexión con el servidor");
}
});
}
});
Related
I'm at a loss on this. I have checked the forums and can't seem to find a solution.
I'm working on creating an ionic app to pull json feeds into the app and have them process. I have one feed setup, in one angular module, that is pulling some data perfectly fine. But when I try to create this second module, the feed var it errors, but if I hard code the URL in the $http.get it works fine.
This code errors with TypeError: Cannot read property 'protocol' of undefined:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get(listings[section])
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
However, making the following change to the $http.get works:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get("http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2")
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
I can't seem to figure out what I've got wrong in my code.
Here is the controller that is running that feed. It works perfectly fine when the URL is hardcoded.
angular.module('mwre.controllers', [])
.controller('PropertiesCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.items = [];
$scope.successGetPropertiesContent = function(data) {
$scope.maxIntro = 100;
$scope.items = data.properties;
for (var i = 0; i < $scope.items.length; i++) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.replace(/<[^>]+>/gm, '');
if ($scope.items[i].smalldesc.length > $scope.maxIntro) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.substr(0, $scope.maxIntro) + '...';
}
}
};
$scope.errorGetPropertiesContent = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property category content',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property category content');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertiesContent($stateParams.propertiesId, $scope.successGetPropertiesContent, $scope.errorGetPropertiesContent);
$scope.goToContent = function(id) {
$state.go('app.properties', { propertiesId: id });
};
})
.controller('PropertyCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.item = null;
$scope.successGetPropertyItem = function(data) {
$scope.item = data;
};
$scope.errorGetPropertyItem = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property listing',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property listing');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertyItem($stateParams.propertyId, $scope.successGetPropertyItem, $scope.errorGetPropertyItem);
});
I'm trying to create a live search function with AngularJS. I got a input field:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the DOM
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Inside the angular controller use a watch expression.
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
You can use watch as #Justin John proposed, or can use ng-change
when using ng-change your controller should look something like this
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
and your html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});
I have a list of places that I am printing list of places, and the idea is when the user clicks on the place it takes the user to another page where the details of the place can be viewed. How can I achieve this?
HTML:Page1
<li ng-repeat="place in places.places">
{{place.name}}
</li>
Page2:
<table ng-controller="UncatCtrl">
<tr>
<td>Name: </td><td>{{place.place.name}}</td>
</tr>
<tr>
<td>placeID: </td><td ng-model="PlaceID">{{place.place.placeID}}</td>
</tr>
</table>
Angular:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/uncatdetails', {
templateUrl: 'templates/uncatpost.html',
controller: 'UnCatPostCtrl'
})
}])
.controller('UnCatPostCtrl', function ($scope, $http) {})
.controller('UncatCtrl', function ($scope, $http) {
$http.get('http://94.125.132.253:8000/getuncategorisedplaces').success(function (data, status, headers) {
$scope.places = data;
console.log(data);
$scope.message = 'Uncategorised places';
})
$scope.showplace = function(placeID) {
$http({method: 'GET', url: 'http://94.125.132.253:8000/getitemdata?ID=' + placeID}).
success(function(data, status, headers, config) {
$scope.place = data; //set view model
console.log(data);
console.log(placeID);
$scope.view = 'templates/detail.html';
})
.error(function(data, status, headers, config) {
$scope.place = data || "Request failed";
$scope.status = status;
$scope.view = 'templates/detail.html';
});
}
})
try it
.when('/uncatdetails/:id', {templateUrl: 'ftemplates/uncatpost.html',
controller: 'UnCatPostCtrl'})
in your HTML
ng-href="uncatdetails/{{place.placeID}}"
in your controller, add this inject $routeParams
$scope.id = $routeParams.id;
So this is a bit complex, but I'll try to get into it, the best I can. In my config.js, I have:
.run(['$rootScope', '$location', 'UserService', 'CompanyService', function($rootScope, $location, UserService, CompanyService) {
$rootScope.globals = {};
$rootScope.$on('login', function(event, data) {
$rootScope.api_key = data.api_key;
CompanyService.get(data.user.company_id);
});
UserService.checkAuth().then(function(response) {
if(response.data.user) {
// Logged in user
$rootScope.$broadcast('login', response.data);
} else {
UserService.logout();
}
});
}]);
which basically checks to see if a user is logged in. If he is, we find out which user he belongs to with the CompanyService:
angular.module('mean').service('CompanyService', ['$http', '$rootScope', function($http, $rootScope) {
var company = this;
company.company_data = {}
company.getCompany = function() {
return company.company_data;
}
company.get = function (company_id) {
return $http({
url: '/api/v1/company/' + company_id,
method: 'GET',
headers: {
api_key: $rootScope.api_key
}
}).success(function(response) {
if(response.status === 'ok') {
company.company_data = response.company;
}
});
};
}]);
Later on in my code, I have a call that relies on the singleton CompanyService to do an API call:
$scope.index = function() {
LocationService.get(CompanyService.getCompany()._id, $routeParams.location_parent_id).then(function(response) {
if(response.data.status === 'ok') {
$scope.locations = $scope.locations.concat(response.data.locations);
}
});
}
if I refresh the page, however, sometimes this call gets executed before we've put data in the CompanyService singleton. How can I use promises to make sure that the LocationService doesn't happen until after we have data in the CompanyService singleton?
One way to do this is without changing your existing code too much would be to create a promise that is fulfilled when CompanyService has data. Note that this code doesn't deal with errors so that still has to be added...
angular.module('mean').service('CompanyService',
['$http', '$rootScope', '$q', function ($http, $rootScope, $q) {
var company = this;
company.company_data = {}
var initializedDeferred = $q.defer;
company.initialized = initializedDeferred.promise;
company.getCompany = function () {
return company.company_data;
}
company.get = function (company_id) {
return $http({
url: '/api/v1/company/' + company_id,
method: 'GET',
headers: {
api_key: $rootScope.api_key
}
}).success(function (response) {
if (response.status === 'ok') {
company.company_data = response.company;
initializedDeferred.resolve(); // reject promise on error?
}
});
};
}]);
$scope.index = function () {
CompanyService.initialized.then(function () {
LocationService.get(CompanyService.getCompany()._id,
$routeParams.location_parent_id).then(function (response) {
if (response.data.status === 'ok') {
$scope.locations = $scope.locations
.concat(response.data.locations);
}
});
});
}
I'm trying to pass data from one controller to another using a factory and for some reason my factory isn't getting recognized in angular seed. Here is my app.js file which I'm declaring my factory
var myApp = angular.module('myApp', ['myApp.controllers','angularFileUpload', 'ngRoute']);
//
//
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/' ,{templateUrl:"/syncproto/partials/videoSlides.html"}, "sync").
when('/scenarios', {templateUrl:"/syncproto/partials/scenarios.html"}, "scenariosCtrl").
when('/scenarios/:id', {templateUrl:"/syncproto/partials/scenarios.html"}, "scenariosCtrl")
}]);
myApp.factory('Data', function() {
var Data;
return {
getData: function () {
return Data;
},
setData: function(value) {
Data = value;
}
};
});
Here is the controller which I'm using the factory Data
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, Data) {
$scope.scenarios = [];
$scope.thumbnails = [];
$scope.init = function(){
console.log('init hit');
$http({ method: 'GET', url: 'http://localhost:3000/scenarios' }).
success(function (data, status, headers, config) {
angular.forEach(data, function(scenario) {
if (scenario.video.length != 0 && scenario.video[0].thumbnailLocation != undefined){
$scope.thumbnails.push(scenario.video[0].thumbnailLocation);
//console.log('thumbnail is' + scenario.video.thumbnailLocation);
$scope.scenarios.push(scenario);
console.log(scenario.video[0].thumbnailLocation);
}
});
//console.log($scope.scenarios);
console.log('success');
}).
error(function (data, status, headers, config) {
console.log('error');
});
console.log($scope.thumbnails);
}
$scope.showVideo = function(scenario){
Data.setData(scenario);
$location.path('/');
//Data.setData($scope.scenarios[$scope.thumbnail.indexOf(thumbnail)]);
}
}])
The problem is that in $scope.showVideo = function(scenario) when i call Data.setData(scenario); I get the error TypeError: Object #<Object> has no method 'setData'
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, Data)
You're missing one argument for the $location service here. It should be
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, $location, Data)