AngularJS update the view when $rootScope changes - javascript

I'm trying to build an angular application that has a sidebar that updates various elements within the DOM.
Currently I have the following configuration:
index.html
<div id="sidebar" ng-controller='SidebarController' ng-class="myclass" class="col-md-2 animated fadeIn" ui-view="sidebar" ng-cloak>
<i ng-click='toggleSidebar()' class='fa fa-chevron-right'></i>
<div class='col-md-12 main'>
<section id='templates'>
<div class="btn-group">
<label class="active btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t1'">Template 1</label>
<label class="btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t2'">Template 2</label>
<label class="btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t3'">Template 3</label>
<label class="btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t4'">Template 4</label>
</div>
</section>
</div>
<div class='col-md-12 other'>
<uib-accordion close-others="oneAtATime">
<uib-accordion-group is-open="status.open" heading="Other fun things you can edit" panel-class="">
<section id='Option'>
<span>Select Option type</span>
<div class="btn-group">
<label ng-model="optionChoice" ng-click='optionType(optionChoice)' class="btn btn-primary" uib-btn-radio="'optiona'">Option A</label>
<label ng-model="optionChoice" ng-click='optionType(optionChoice)' class="active btn btn-primary" uib-btn-radio="'optionb'">Option B</label>
<label ng-model="optionChoice" ng-click='optionType(optionChoice)' class="btn btn-primary" uib-btn-radio="'optionc'">Option C</label>
</div>
</section>
</uib-accordion-group>
</uib-accordion>
</div>
</div>
<!-- MAIN CONTENT -->
<div id="main-container" class="col-md-10 animated fadeIn" ui-view="mainContent" ng-cloak></div>
and the controller associated with it SidebarController.js:
application.controller('SidebarController', ['$scope', '$rootScope', '$http', '$state', function ($scope, $rootScope, $http, $state, $translate) {
//Select Option
$rootScope.optiona= false;
$rootScope.optionb= true;
$rootScope.optionc= false;
$scope.optionType= function (optionChoice) {
switch (optionChoice) {
case "optiona":
$rootScope.optiona= true;
$rootScope.optionb= false;
$rootScope.optionc= false;
break;
case "optionb":
$rootScope.optionb= true;
$rootScope.optiona= false;
$rootScope.optionc= false;
break;
case "optionc":
$rootScope.optionc= true;
$rootScope.optionb= false;
$rootScope.optiona= false;
break;
}
}
}]);
Then I have another template called home.html:
<div id='mybtn' ng-if="general.optiona" class='alt-btn btn btn-primary' role="button">Option A</div>
<div id='mybtn' ng-if="general.optionb" class='alt-btn btn btn-primary' role="button">Option B</div>
and the controller MainPageController.js:
application.controller('MainPageController', ['$scope', '$rootScope', '$http', '$state', '$window', function ($scope, $rootScope, $http, $state, $window, $translate, $location) {
$scope.general = {
optiona: $rootScope.optiona,
optionb: $rootScope.optionb,
optionc: $rootScope.optionc
}
}]);
My hope would be that the relevant div would show depending on the option selected but that is not the case. Is there a way the MainPageController.js will automatically update when the SidebarController.js updates $rootScope?
Also I know its not best practice to store things in the $rootScope but for this instance I've opted to do it.
I'm also recieving no errors in the console window. The application is running within my browser fine but I'm unable to update the interface accordingly
any help much appreciated!

Do not use $rootScope, this is not what it is meant for.
please read about angular Services and use them instead to share data across different parts of youre application.
any way for youre question - if you want to detect a change in the $rootScope use the $watch function, you should read the documentations anout that also.
Good luck.

Related

HTTP GET request to StackExchange API doesn't return in AngularJS app

I made a GET request to get a user by ID, but it doesn't seem to work (nothing happens at all). I am using my user ID so I know the user exists. I get no error message.
Here is my AngularJS code :
myApp.controller('mainpage', ['$scope', '$http', '$resource', 'AuthService', 'sharedPropertie', function ($scope, $http, $resource, AuthService, sharedPropertie) {
$scope.test='7194489';
$scope.user=[];
$http.get('https://api.stackexchange.com/2.2/users/'+$scope.test+'?order=desc&sort=reputation&site=stackoverflow')
.then(function(value) {
console.log('value in mainpage'+value);
$scope.user.push(value);
});
}]);
And my view:
<body>
<div ng-controller="meetupsController">
<div ng-controller="routeController">
<a ng-click='gotoprive()' class="btn btn-default">Prive</a>
<a ng-click='gotopublicforum()' class="btn btn-default">Forum public</a>
<a ng-click='logout()' class="btn btn-default">logout</a>
<a ng-click='topublicforumgw()' class="btn btn-default">public forum</a>
<a ng-click='toprivateforumgw()' class="btn btn-default">private forum</a>
<a ng-click='toaccesscontrol()' class="btn btn-default">accesscontrol</a>
<a ng-click='tomessengergw()' class="btn btn-default">messenger</a>
<a ng-click='topopulatedforumgw()' class="btn btn-default">populated forum</a>
</div>
<h1>{{user[0]}}</h1>
</div>
</body>
You are using the wrong controller, so your controller's code (including the $http.get) never gets executed in the first place. Change <div ng-controller="meetupsController"> to <div ng-controller="mainpage"> so the mainpage controller's code gets executed.

ng-change and ng-click not triggering events in controller

I'm trying to create a radio type button selection in AngularJS. Here is my code.
HTML code:
<!-- Page Content -->
<div id="page-wrapper">
<div class="container-fluid">
<h3 class="page-header">Create Products</h3>
<div class="media-list" data-toggle="buttons">
<label class="btn btn-default col-md-2 custom-thumbnail">
<input type="radio" ng-model="platformSel" ng-change="tileSelect(value)" value="win" name="platform-selection" id="win-tile" >
<i class="center-block fa fa-windows fa-5x"></i>
<span class="text-center">Windows</span>
</label>
<label class="btn btn-default col-md-offset-custom col-md-2 custom-thumbnail">
<input type="radio" ng-model="platformSel" ng-change="tileSelect(value)" value="mac" name="platform-selection" id="mac-tile">
<i class="center-block fa fa-apple fa-5x"></i>
<span class="text-center">MAC</span>
</label>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
Controller code:
(function() {
'use strict';
function config($routeProvider) {
$routeProvider
.when('/createProduct', {
templateUrl: 'app/components/createProduct/createProductView.html',
controller: 'createProductCtrlr'
});
}
function createProductCtrlr($scope, $rootScope, $location) {
$scope.platformSel = '';
$scope.tileSelect = function(target) {
console.log(target + " selected");
};
}
angular
.module('pacman')
.controller('createProductCtrlr', ['$scope', '$rootScope', '$location', createProductCtrlr])
.config(['$routeProvider', config]);
})();
I don't see any call happening in 'tileSelect' function. I have no clue why.
Any help is appreciated. I'm new to Angular JS.
Is there any error in JavaScript console? As mentioned before you are missing ng-app and ng-controller directives.
<div id="page-wrapper" ng-app="pacman" ng-controller="createProductCtrlr">
The rest of the code almost correct but since you bind the radio to a model variable there is no need for passing argument in ng-change function.
$scope.tileSelect = function() {
console.log($scope.platformSel + " selected");
};
Check this fiddle
Debugging and fixing stuff is real hard. Not as simple as writing code from scratch.
The reason being is, 'data-toggle=buttons' just toggles the bootstrap UI and doesnt make any function calls. Remove the line from html line where class="media-list" and it works.
Answer:
data-toggle="buttons" just toggles the twin button group. Doesnt allow to make function calls.

I am trying to call text from input using angular js

I am trying to call text that has been added to an input using Angular JS, however in my console log I keep getting undefined.
<div ng-controller="favouritesController" class="col-xs-12 favList">
<input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
<ul>
<li ng-repeat="weatherList in weatherLists" class="col-xs-12">
<span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
<div class="col-xs-12 col-sm-2">
<button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
<div class="col-xs-12">
<input type="text" ng-model="serverip"/>
<button ng-click="save(serverip)">Save</button>
</div>
</div>
</li>
</ul>
</div>
js code
myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
$scope.save = function(){
console.log($scope.serverip)
}
})
You don't need to pass the parameter to the save function (and your definition of save doesn't include it).
Change the button to:
<button ng-click="save()">Save</button>
Or either accept the parameter in the function declaration:
$scope.save = function(serverip){
console.log(serverip)
}
ng-repeat creates a new scope, inheriting from the scope above it. You are assigning serverip to this newly created scope. Thus, $scope in the favouritesController's context has no record of this. You should accept a parameter in your save function and log that (as you are passing this function the argument, anyways.)
Edit:
or, as an alternative... Expose a property that will be inherited by ng-repeat:
Controller:
myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
$scope.ip = { serverip:'' };
$scope.save = function(){
console.log($scope.ip.serverip)
}
});
Template
<div ng-controller="favouritesController" class="col-xs-12 favList">
<input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
<ul>
<li ng-repeat="weatherList in weatherLists" class="col-xs-12">
<span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
<div class="col-xs-12 col-sm-2">
<button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
<div class="col-xs-12">
<input type="text" ng-model="ip.serverip"/>
<button ng-click="save()">Save</button>
</div>
</div>
</li>
</ul>
</div>

angularjs $scope.watch text field error?

i have used local storage to filter listpage .i have text box with clear button
when i clear button its not working becoze of that $scope.watch.if i enter values in text box also $scope.watch is not allowed the values how to avoid this error when i click clear button.when i clear or ng-model changes i need to pick current value based on that value list should come
.controller('ListingCtrl', [
'$scope', '$http', '$location', '$window', '$filter','$ionicPopover','$ionicLoading',
function($scope, $http, $location, $window, $filter, $ionicPopover, $ionicLoading) {
$scope.$watch(function() {
var searchstore =window.localStorage.getItem("searchstore");
console.log(searchstore);
$scope.query=searchstore;
})
$scope.clearSearch = function()
{
$scope.query = '';
};
$http.get('*****').success(function(data,dealers,response)
{
$scope.dealers = data;
});
}])
<!-- begin snippet: js hide: false -->
<div class="bar bar-header item-input-inset">
<label class="item-input-wrapper" >
<i class="icon ion-ios-search placeholder-icon"></i>
<input type="text" placeholder="Search" ng-model="query" >
</label>
<button class="button button-icon ion-ios-close-outline" ng-click="clearSearch()" id="iconcolor" >clear</button>
</div>
<div class="list card" data-ng-init="nearme()" data-ng-repeat="dealer in dealers | filter:query ">
<div class="item item-thumbnail-left item-icon-right" href="#">
<h2>{{dealer.Store_Name}}</h2>
<p>{{dealer.S_Address.area}} {{dealer.S_Address.city}}</p>
<p>{{dealer.S_Services}}</p>
</div>
</div>
This should work like you want it.
$scope.$watch(function() {
return window.localStorage.getItem("searchstore")
},
function(searchstore) {
$scope.query = searchstore;
});
$scope.clearSearch = function() {
// You could remove aswell, but I prefer setting it empty
// window.localStorage.removeItem("searchstore");
window.localStorage.setItem("searchstore", "");
};

Controller Function is not getting called on ng-click

This is my View Code
<div ng-controller="signupCtrl">
<ul class="list-group" >
<li class="list-group-item">
<div class="form-group">
<input type="text" ng-model="signupCtrl.firstName">
</div>
...
</div>
<div class="form-group">
<div class="pull-right">
<button ng-click="signupCtrl.signupUser()">Register</button>
</div>
</div>
</li>
</ul>
</div>
Update- This is my Controller Code ##
someAppControllers.controller('signupCtrl', [
'$window',
'$scope',
'HttpReqHandlerService',
'$location',
'localStorageService'],
function($window, $scope, HttpReqHandlerService,
$location, localStorageService) {
$scope.signupUser=function signupUser() {
alert("hello");
}]);
The button is not calling signupUser function in my controller
Use $scope.signupUser instead of this.signupUser
Change you code as
someAppControllers.controller('signupCtrl', ['$window', '$scope',
function ($window, $scope) { // Here you have to define function an pass window and scope
$scope.signupUser = function signupUser() {
alert("hello");
};
}
]);
Additionally, You have syntax error.
HTML
Instead of
<input type="text" ng-model="signupCtrl.firstName">
<button ng-click="signupCtrl.signupUser()">Register</button>
Use
<input type="text" ng-model="firstName">
<button ng-click="signupUser()">Register</button>
You've written your markup as though you used the controller as syntax. To make it work just change your ng-controller="signupCtrl" to ng-controller="signupCtrl as signupCtrl";

Categories

Resources