Cookie-Issue in Angular - angularjs

i try to store Data in Cookies in Angular. It doesnt seem to work somehow.
I made this function to store the cookie
Store the cookie
$scope.goLove = function(name,id){
var thebestCity = name;
var bestCityID = id;
alert("Du magst: " + thebestCity + " mit der ID: " + bestCityID);
$cookies.put('favourite', thebestCity);
var favouriteCity = $cookies.get('favourite');
alert(favouriteCity);
}
Since the alert works i would think the data is stored inside the cookie. So i tried to open it with another function:
Access the cookie (not working)
cityApp.controller('cookieReader', function($scope, $cookies){
$scope.tellmeCookie = function($scope, $cookies){
var cookieInfo = $cookies.get('favourite');
alert(cookieInfo);
}
});
Somehow the function keeps breaking.As soon as i put the $cookies.get inside there is no more response! Could you please tell me why? Thank you very much!

Firstly have you include angular-cookies.js
Has the module been included in your app
angular.module('app', ['ngCookies']);
On your example that isnt working it kind of looks like your trying to make your code minify safe
you could change it to something like this
cityApp.controller('cookieReader',
["$scope", "$cookies", function($scope, $cookies){
$scope.tellmeCookie = function(){
var cookieInfo = $cookies.get('favourite');
alert(cookieInfo);
}
}]
);

Related

Routing.generate() module (FriendsofSymfony/FOSjsRouting Bundle)

I am trying to create a multiple input tags-input field in AngularJS, where I also want to add auto complete, so that on typing atleast 3 letters in the input field, the already existing tag names in the database appear as suggestions in the dropdown.
Here is the problem:
I am using Routing.generate() module of the FOSjsRouting Bundle to call the controller action inside the javascript code (the action in-turn returns the following JsonResponse object):
Here is the controller code:
/**
* #Route("/jsondata", options={"expose"=true}, name="my_route_to_json_data")
*/
public function tagsAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT t.text
FROM AppBundle:Tag t
WHERE t.id > :id
ORDER BY t.id ASC'
)->setParameter('id', '0');
$tagsdata = $query->getScalarResult();
$response = new Response(json_encode($tagsdata));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
Here is the AngularJS code:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.loadTags = function(query) {
return $http.get(Routing.generate('my_route_to_json_data'));
};
});
Here is the result I get:
Now when I save the Json response in tags.json and call it without using Routing.generate() module:
var app = angular.module('plunker', ['ngTagsInput']);
app.controller('MainCtrl', function($scope, $http) {
$scope.loadTags = function(query) {
return $http.get('http://localhost/AngularTags/web/js/tags.json');
}
});
I get the perfectly working result:
Now I know the problem lies with proper usage of Routing.generate(). Since I am new to AngularJS and am just learning how to debug in console(which m loving by the way), m not entirely sure if I can figure out the problem on my own. Any help is appreciated.
n m sorry the post became too long, just wanted to make it clear.
So, awaiting response...
This is not a problem with AngularJS, this is a problem of variable scope in JavaScript.
Did you import the scripts in your HTML as specified in the documentation?

AngularJS Amplitude Service Not Acting as Singleton

I have recently posted a similar question, but this is not a duplicate.
Apologies for the code heavy post but I wanted to provide as much context as possible. I am having an issue with defining the analytics tool, 'Amplitude' as a service in my Angular.js application. Services are supposed to act as singletons throughout an application (source), so I am confused to be getting the following behavior.
In my app.js file, I call AmplitudeService.logEvent('EVENT_NAME') in a .run function which successfully logs the event to Amplitude. Note: Console.log(AmplitudeService) returns an object with all the correct functions here.
However, when I call AmplitudeService.logEvent('EVENT_NAME') within any other controller, such as header.js I do not ever see any data in my Amplitude dashboard. Note: Console.log(AmplitudeService) returns an identical object within header.js to the one returned from app.js
Would appreciate any and all insight!
P.S. The official AmplitudeJS SDK is here. I am trying to implement it through this wrapper.
AmplitudeService.js (source)
Note: If you check the author's syntax, he returns an object at the end of his service. In my research, I've read to use the "this" keyword when defining Service functions (source), and that you don't need to return an object as you would with a Factory, so I have updated it accordingly.
angular.module('AmplitudeService', [])
.service('AmplitudeService',
['$amplitude', '$rootScope', 'amplitudeApiKey', '$location',
function ($amplitude, $rootScope, amplitudeApiKey, $location) {
this.init = function() {
$amplitude.init(amplitudeApiKey, null);
}
this.identifyUser = function(userId, userProperties) {
$amplitude.setUserId(userId);
$amplitude.setUserProperties(userProperties);
}
this.logEvent = function(eventName, params) {
$amplitude.logEvent(eventName, params);
}
}]);
angular-amplitude.js (source)
This allows access to "$amplitude" throughout the application
(function(){
var module = angular.module('angular-amplitude', ['ng']);
module.provider('$amplitude', [function $amplitudeProvider() {
this.$get = ['$window', function($window) {
(function(e,t){
var r = e.amplitude || {};
var n = t.createElement("script");
n.type = "text/javascript";
n.async = true;
n.src = "https://d24n15hnbwhuhn.buttfront.net/libs/amplitude-2.2.0-min.gz.js";
var s = t.getElementsByTagName("script")[0];
s.parentNode.insertBefore(n,s);
r._q = [];
function a(e){
r[e] = function(){
r._q.push([e].concat(Array.prototype.slice.call(arguments,0)));
}
}
var i = ["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];
for(var o = 0; o < i.length; o++){
a(i[o])
}
e.amplitude = r
}
)(window,document);
return $window.amplitude;
}];
}]);
return module;
}());
App.js
angular.module('app', [
'ngRoute',
'angular-amplitude',
'AmplitudeService',
])
.run(['AmplitudeService', function(AmplitudeService){
console.log(AmplitudeService); // Outputs 'Object {}'
AmplitudeService.init();
*AmplitudeService.logEvent('LAUNCHED_SITE'); // This logs the event*
console.log(AmplitudeService); // Outputs 'Object {}'
}])
Header.js
angular.module('app.common.header', [])
.controller('HeaderCtrl', [ '$rootScope', '$scope', '$location','$route', '$window', 'AmplitudeService', function($rootScope, $scope, $location, $route, $window, AmplitudeService){
$scope.goToSearch = function(term) {
$location.path('/search/' + term);
console.log(AmplitudeService); // Outputs 'Object {}'
*AmplitudeService.logEvent('SEARCHED');* // This does not log the event
};
}]);
Update: I have tried switching the Service to a Factory and that did not generate any new results.
Found the solution and hope this is helpful to anyone that comes across this. My solution was to initialize the SDK by calling AmplitudeService.init() within a .run() function within app.js, which initialized an amplitude object within my window. From there forward, I included $window as a service in each of my controllers and called $window.amplitude.logEvent('event_name_here');
Feel free to contact if you have questions. Thanks.
We had similar issues on a large project and we created a wrapper providing a directive to init Amplitude and a service to provide the logEvent and sendUserId.

Why is my sanitized img tags coming up empty?

The following code is a function that uses parameters. When I alert the variable, the string appears exactly how it is supposed to.
$scope.createMap = function(size,scale,center,zoom,style){
$scope.myMap = "<img ng-src='https://maps.googleapis.com/maps/api/staticmap?size="+size+"&scale="+scale+"&center=IL"+center+"&style="+style+"&zoom="+zoom+"'>";
alert($scope.myMap);
return;
}
However, on the HTML page where this is binded to:
<div ng-bind-html="myMap" id="myStaticMap">
MAP GOES HERE
</div>
The area is empty and when I "inspect element" there is <img></img>, so it is registering it is an image, but coming up empty.
Same thing happens here:
$scope.displayPage = function(page){
$scope.siteName = $scope.names[page].PageName;
$scope.logo = "<img ng-src='"+$scope.names[page].logo+"'>";
alert($scope.logo);
$scope.createMap($scope.names[page].Size,$scope.names[page].Scale,$scope.names[page].Center,$scope.names[page].Zoom,$scope.names[page].Style);}
Where the parameter is being used a little bit differently. But again, the alert for $scope.logo is alerting the correct string but there is <img></img> where it is supposed to be binded. $scope.siteName is binded fine, but then, it is not binding any HTML.
I am using the sanitize module:
var app = angular.module('myApp', ["ngSanitize"]);
(the script is placed last in my list of external references)
So I am not sure what is wrong here.
UPDATE: So I did the suggestion in answer below and it is working when I change ng-src to src so that is awesome. However, I am getting the error below in my web console, anyone know why? I get it whether I use ng-src or src:
"Error: html.indexOf is not a function
htmlParser#http://code.angularjs.org/1.0.3/angular-sanitize.js:205:12
$sanitize#http://code.angularjs.org/1.0.3/angular-sanitize.js:119:1
ngBindHtmlWatchAction#http://code.angularjs.org/1.0.3/angular-sanitize.js:420:1
Yd/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:110:371
Yd/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:113:360
m#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:72:452
w#https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:77:463
ye/https://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:79:24
var app = angular.module('myApp', ["ngSanitize"]);
app.controller('customersCtrl', function($scope, $http, $sce) {
When you parse html from within your controller, you have to use the $sce dependency from angular, in order to mark the html as "trusted":
angular.module("yourModule").controller("yourController",
["$scope", "$sce", function ($scope, $sce) {
$scope.displayPage = function(page){
$scope.siteName = $scope.names[page].PageName;
$scope.logo = $sce.trustAsHtml("<img ng-src='"+$scope.names[page].logo+"'>");
alert($scope.logo);
$scope.createMap($scope.names[page].Size,$scope.names[page].Scale,$scope.names[page].Center,$scope.names[page].Zoom,$scope.names[page].Style);}
}
]);

firebase snapshot will not return value

Another Question here,
I am using firebase and angular js, and trying to return data from my database to the console log using this code :
function userCtrl($scope){
$scope.userName="";
$scope.myData = new Firebase ("https://yjyc-signup.firebaseio.com/Entries");
$scope.users={};
$scope.saveUser = function(){
$scope.myData.push({userName: $scope.userName});
$scope.userName="RESET";
};
$scope.myData.on('value', function(snapshot) {
$scope.users = snapshot.val();
console.log("Author: " + $scope.users.name);
});
but the console return "Author: Undefined" although I have a value in my database of a name.
is anybody can help me that would be amazing
When using AngularFire you need to sync the reference before you can get any data from it. Also you're trying to use a Firebase function that doesn't exist for AngularFire as far as I'm aware. Instead try to register a $watch function in your controller and each time that $watch executes you grab the information from the reference. Something like this:
myApp.controller('UserCtrl', ['$scope', function($scope) {
$scope.$watch('watchedExpression', function() {
var ref = new Firebase ("https://yjyc-signup.firebaseio.com/Entries");
var syncedRef = $firebase(ref);
console.log('Author:' + syncedRef.name); //You need to change this path to work with your Firebase tree structure
});
}]);
If you don't want to register a $watch function you can look at the threeway data-binding, you can look at this here in the AngularFire documentation.

Service is not getting hit

Hi I am new to angularjs and am trying to get some information from a service call using Restangular, I am facing trouble while retrieving the data. Following is the code for the js file
angular.module('sol.user', ['restangular'])
.controller('sol.user.UserController',UserController)
.factory('sol.user.UserFactory',UserFactory);
UserFactory.$inject =['$rootScope', 'Restangular'];
UserController.$inject =['$rootScope', 'Restangular','sol.user.UserFactory'];
function UserFactory($rootScope, Restangular) {
alert("1");
var UserController = {};
var userDetails = Restangular.one('/user/userDetails');
var a = userDetails.post();
UserController = a;
return UserController;
}
function UserController($rootScope, Restangular, user){
$state.go('home.search');
}
function RestConfig(RestangularProvider) {
RestangularProvider.setBaseUrl('http://10.98.3.2:9081/CustomerService/');
RestangularProvider.setDefaultHttpFields({cache: false,timeout: 20000});
RestangularProvider.setDefaultHeaders({brand: "wp",userBsb: "032000"});
;
RestangularProvider.setFullRequestInterceptor(RequestInterceptor);
}
I am not able to hit to the service url, while i am able to retrieve the data using RESTClient.
What seems to be the problem?
Also please tell me whats the difference between Restangular.all/one/

Resources