update page with localstorage value angular watcher - javascript

controller 1 where we set value
$scope.view = function() {
$scope.usethis = "&1=test";
$localStorage.change = $scope.usethis;
}
Now in my second controller I grab the value to update:
$scope.Data = function() {
var URL;
$scope.update = $localStorage.change;
URL = "?test";
if ($scope.update){
URL = "?test" + $scope.update;
}
}
and finally my watcher:
$scope.$watch(function () { return $localStorage.change; },function(newVal,oldVal) {
if(oldVal!==newVal) {
$scope.update = newVal;
} }) ;
On page refresh I can update the query, it uses the values as required. However it does not update without a refresh, so wondering if an issue with the watcher.

Related

Load data from Firebase using AngularJS immediately

I am trying to make a comments section on my website. I have properly linked all my files and getting data from Firebase is working. But, the comments only load after I either click on something or enter text in the "Add comment" field; it does not show the comments instantly when the page loads. Does anyone know why?
Relevant code: (placed at the top of my controller)
$scope.comments = {};
database.ref('comments').on('value', function(items) {
$scope.comments = items.val();
});
$scope.comment = function() {
database.ref('comments').push($scope.newComment);
$scope.newComment = "";
};
Use $scope.$apply
$scope.comments = {};
database.ref('comments').on('value', function(items) {
$scope.$apply(function () {
$scope.comments = items.val();
});
});
$scope.comment = function() {
database.ref('comments').push($scope.newComment);
$scope.newComment = "";
};

why angular service attribute changes can not affect the relative value in the controller scope?

Here is my code brief:
controller:
angular.module('testApp').controller('TestCtrl', function ($scope, EssayRsc, EssaySvc) {
$scope.pageInfo = EssaySvc;
}
service:
angular.module('testApp').service('EssaySvc', function (EssayRsc, $document, $rootScope) {
var count = 1;
var essayList = [{title:11111},{title:11111},{title:11111},{title:11111},{title:11111},{title:11111},{title:11111}];
var pageNum = null;
var pages = null;
$document.scroll(function () {
if ($document.height() == ($document.scrollTop() + angular.element(window).height())) {
EssayRsc.get({pageSize:count}, function (resp) {
essayList = essayList.concat(resp.list);
pageNum = resp.pageNum;
pages = resp.pages;
this.essayList = essayList;
// this changes here but not changes in the controller
console.log(this.essayList);
});
}
});
this.essayList = essayList;
this.pageNum = pageNum;
this.pages = pages;
})
html:
<ul class="no-bullet" ng-repeat="essay in pageInfo.essayList">
<li class="essay-query-li" ng-click="viewEssay(essay.id)">{{essay.title}}</li>
</ul>
This is my question:
I want to set a listener in a service,so erverytime I scroll to the bottom of the window it can load one record.
but everytime essayList attribute in the service changed,but in the controller and view it never change, i really cannot figure out why and how to solve it,if you know the answer please tell me, thanks a lot!

Having issue related to $scope variable in AngularJS. Value is not changed in UI

The value of image isn't updated in the UI, even though the scope variable is changed.
Main Controller :
$scope.TVuploadModal = function($files) {
$scope.TvTemp.file = $files[0];
$scope.TvTemp.fileName = $files[0].name
var fileReader = new FileReader();
fileReader.readAsDataURL($scope.TvTemp.file);
fileReader.onload = function(e) {
$timeout(function() { $scope.TvTemp.file.dataUrl = e.target.result; });
};
$scope.ResourceOpenBannerImageCrop('lg');
}
$scope.ResourceOpenBannerImageCrop = function(size) {
$modal.open({ templateUrl: 'BannerImageCrop.html', controller: 'resourceBannerImageCropCtrl', backdrop: 'static', size: size, scope: $scope,
resolve: {
TVImages: function () {
return $scope.TVImages;
}
}
}).result.then(function(images) {
console.log("Hello.....");
console.log($scope.TVImages);
/*$scope.TVImages = images;*/ });
};
resourceBannerImageCropCtrl :
app.controller('resourceBannerImageCropCtrl', function($scope,$rootScope,TVImages,$routeParams, $modalInstance, $location, $upload,ResourceAdditionStepsUpdateService,mediaUploadService) {
$scope.myCroppedImage = '';
$scope.TVImages1 = TVImages;
$scope.showSpinner = false;
$scope.imageCrop = function() {
$scope.showSpinner = true;
var requestMap = { imagedata:$scope.myCroppedImage, fileName:$scope.TvTemp.fileName, fileType:"Resource Images", userId: $rootScope.currentLoggedInUserId }
var saveResourceImages = mediaUploadService.saveImagesToUserBucket(requestMap, function(response) {
$scope.showSpinner = false;
if (response.isSuccess) {
var image = {}
image.uniqueKey = response.data.uniqueKey
image.fileUrl = response.data.url
image.fileType = "Resource Images"
image.description = $scope.description
image.type = "IMAGE"
image.s3UploadStatus = response.data.s3UploadStatus
ResourceAdditionStepsUpdateService.saveResourceImages({resourceId : $scope.resourceMetadata.resourceData.id , image : image},function(response){
console.log(response.data.mediaList);
$scope.showSpinner = false;
if(response.isSuccess){
$scope.TVImages1 = [];
$scope.TVImages1 = response.data.mediaList;
if (!$scope.$$phase) {
$scope.$apply();
}
}
});
$modalInstance.close(/*$scope.volcareTVImages*/);
}
})
};
$scope.cancel = function() { $modalInstance.dismiss('cancel'); };
});
HTML:
<div class="col-sm-4 mb20" ng-repeat="image in TVImages">
//content
</div>
I am passing the scope variable (i.e $scope.TVImages) in resolve as you can see in the code I am updating the $scope.TVImages1.
As per my understanding of two way data binding, if $scope.TVImages1 is updated, then $scope.TVImages should also update via the resolve.
I also tried using $scope.$apply, but that didn't work.
What am I doing wrong?
Qasim,
Some days ago, I was also facing this kind of issue while updating the value of $scope variable which is assigned as ng-repeat variable in the the view.
Could you please try to use following line instead of $scope.TVImages
$rootScope.TVImages that will update the view variable.
Please let me know if you still facing some problem.

How update main controller $scope since a song controller in Angularjs

i am working with angular and Parse.com and I have a problem:
I have a "mainController" that its in all the html document and a routeProvider with some pages and controllers.
function mainController($scope)
{
$scope.logeado = (Parse.User.current()!=null)
if (Parse.User.current()==null)
{
$scope.showuser=""
}
else
{
$scope.showuser=Parse.User.current().get('username')
}
$scope.logout = function()
{
Parse.User.logOut();
$scope.logeado = (Parse.User.current()!=null);
$scope.$apply();
}
};
One of this controller is "loginController". In this controller make the login, but my problem is:
If i logout, the function is in the maincontroller and this ng-show="logeado" change because the variable is inside, but if i login since logincontroller, i can change "Parse.User.current()" but $scope.logeado isn't update, and i need update all the page to see the changes.
How can i do to update de variable?
One of the way to solve problem is to implement pattern observer. Let
Parse.User.current notify about his state.
function mainController($scope){
Parse.User.current.onChange(function () {
$scope.logeado = (Parse.User.current()!=null);
if (Parse.User.current() == null) {
$scope.showuser=""
} else {
$scope.showuser=Parse.User.current().get('username')
}
});
$scope.logout = function() {
Parse.User.logOut();
};
};
Finally, I have make a function in mainController($scope):
$scope.login2= function(){
$scope.logeado = (Parse.User.current()!=null);
if (Parse.User.current() == null)
{
$scope.showuser=""
}
else
{
$scope.showuser=Parse.User.current().get('username')
}
};
and call it since loginController($scope) because $scope.login2 is inherited in this.

Make switch directive

I'm trying to pass in a $scope that I want to change the value on.
These are two switch button on the same page that.
View
<div class="input">
<switch state="false" toggle="user.emailNotification">
<flip></flip>
</switch>
</div>
<div ng-click="saveNotifySettings()" class="button fill primary">Vista</div>
Controller
app.controller('notifySettingCtrl', function($scope, Users){
Users.get().$promise.then(function(data) {
$scope.user = data;
console.log($scope.user.emailNotification);
});
$scope.saveNotifySettings = function() {
console.log("PUT the new value for the switch");
};
});
When I press the button the state changes from false to true
First I want to init the state with the existing value from $scope.user.emailNotification and then change it and pass the changes to the controller.
The beginning of the my directive.
switch directive
(function() {
define(['angular', 'app', 'underscore'], function(angular, app, _) {
app.directive('switch', function() {
return {
restrict: 'E',
scope: {
value: '&toggle',
},
link: function(scope, element) {
var x = scope.value();
element.bind('mouseenter', function() {
console.log(x);
});
var $element = angular.element(element),
uniqueId = _.uniqueId('switch-'),
state = $element.attr('state');
state = typeof state === 'undefined' ? false : state;
$element.data('uniqueId',uniqueId)
.attr('state',state)
.attr('alive',true);
$element.on('click.'+uniqueId,function(){
if (state === true) {
$(this).attr('state',false);
state = false;
} else {
$(this).attr('state',true);
state = true;
}
});
}
};
});
});
}).call(this);
I'm very new at creating directives, so any help is well appreciated.
I have spend way to much time at this and it getting frustrating :/
Update:
I have created http://jsfiddle.net/HuLn4/. I have taken the pointers from you and refactored.
TLDR: I'm trying to create directive by sending in the model that I want to change in this case user.emailNotification and when the element is clicked on it changes the value from true/false and false/true and stores it back to the controllers $scope.user so it can be PUT to server and the state attribute is only to tell the look on the switch and for the initialize on the button ( on / off ).

Categories