passing ng-show between two different controllers - angularjs

I have a button which falls into Controller B and two block of HTML code which kind of falls under controller A...............and button falls into one block of HTML code
Example:
<div ng-controller="A">
<div ng-show="now">
<div>
<Button ng-controller="B"></Button>
</div>
</div>
<div ng-show="later">
</div>
</div>
On one button click I show up now block and later on button click of B controller I kind of hide now block and display later block.
How do I achieve this functionality?? I am not able to pass ng-show varibales between two different controller files......what should I use???

Hope this helps...!
angular.module('app', [])
.controller('A', function($scope) {
console.log('A');
$scope.state = {
now: true
};
$scope.showLater = function() {
$scope.state.later = true;
};
})
.controller('B', function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="A" ng-app="app">
<div ng-show="state.now">
<div>
<button ng-controller="B" ng-click="showLater()">Show Later</button>
</div>
</div>
<div ng-show="state.later">LATER
</div>
<p> <pre ng-bind="state | json"></pre>
</p>
</div>

You could use a simple service that stores the state.
Example:
angular.module('mymodule').service('ActiveService', function() {
var service = {};
var status = false;
service.getStatus = function() {
return status;
}
service.toggle = function() {
status = !status;
}
return service;
})
And in your controller:
angular.module('mymodule').controller('SomeController', function(ActiveService) {
$scope.status = ActiveService.getStatus;
})
The Angularjs service is a singelton, so it will hold your values for you across different controllers, directives or pages.
Could also be used directly:
// Controller
$scope.service = ActiveService;
// Html
<div ng-show="service.getStatus()">
...
</div>

You can also achieve this by declaring the variable in $rootScope and watching it in controller A,
app.controller('A', function($scope, $rootScope) {
$rootScope.now = true;
$rootScope.later = false;
$rootScope.$watch("now", function() {
$scope.now = $rootScope.now;
$scope.later = !$rootScope.now;
})
});
In Controller B, you just change the value of now based on previous value like this on ng-click,
app.controller('B', function($scope, $rootScope) {
$scope.testBtn = function() {
$rootScope.now = !$rootScope.now;
}
});
I have implemented a button within different divs(now and later) in a plunker,
http://embed.plnkr.co/xtegii1vCqTxHO7sUNBU/preview
Hope this helps!

Related

watch rootScope variable to change the progressBar value

app.controller("ListController1", ['$rootScope',function($rootScope) {
$rootScope.progressBar=10;
$rootScope.$watch(
function() {
return $rootScope.progressBar;
},
function(){
alert($rootScope.progressBar);
alert("changed");
},true)
}]);
app.controller("ListController2", ['$scope','$rootScope',function($scope,$rootScope) {
$scope.save=function() {
$rootScope.progressBar=20;
}
}]);
I want progressBar value form ListController2 to be reflected back in Listcontroller1. It seems i am doing something wrong with it. Please help any one. thank u.
Rather than sharing state with $routeScope, you should consider creating a service to share the state of the progress bar - this is one of the use cases of services.
When the save button is pressed in the code below, it updates the value in progressService. The value from progressService is watched in the first controller and the view is updated accordingly.
You can add progressService to as many controllers as you'd like.
var app = angular.module("app", []);
app.factory("progressService", [function() {
var service = this;
service.progressBar = 0;
return service;
}]);
app.controller("ListController1", ["$scope", "progressService", function($scope, progressService) {
progressService.progressBar=10;
$scope.progress = progressService.progressBar;
$scope.$watch(
function() {
return progressService.progressBar;
},
function(newValue) {
$scope.progress = newValue;
});
}]);
app.controller("ListController2", ['$scope','progressService',function($scope,progressService) {
$scope.save=function() {
progressService.progressBar=20;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="ListController1">
Progress: {{progress}}
</div>
<div ng-controller="ListController2">
<button ng-click="save()">Save</button>
</div>
</div>

Factory value not updated in model ...what I am doing wrong?

I am new to angular-js. I have two controllers (welcomeContoller,productController) and both handling the same model within the factory.
When the model getting updating by one controller(productController) it should reflect the update in another controller. (welcomeContoller)
But its not happening now.
HTML code :
<body ng-app="myApp">
<div ng-controller="welcomeContoller">
{{totalProductCnt}}
</div>
<div ng-controller="productController">
<div class="addRemoveCart">
<span class="pull-left glyphicon glyphicon-minus" ng-click="removeProduct()"></span>
<span class="pull-right glyphicon glyphicon-plus" ng-click="addProduct(1)"></span>
</div>
</div>
JS code
var myApp = angular.module("myApp", ['ui.bootstrap']);
myApp.factory("productCountFactory", function() {
return {
totalProducts:0
};
});
myApp.controller("welcomeContoller", function($scope, productCountFactory)
{
$scope.totalProductCnt = productCountFactory.totalProducts;
});
myApp.controller("productController", function($scope, productCountFactory) {
$scope.addProduct = function() {
productCountFactory.totalProducts++;
alert(productCountFactory.totalProducts);
};
$scope.removeProduct = function() {
if(productCountFactory.totalProducts >=1)
productCountFactory.totalProducts--;
alert(productCountFactory.totalProducts);
};
});
Even after the addProduct is called the totalProductCnt is displaying as zero. I want to display the value for each increment.
Plunkr Link
Put the factory object reference on scope:
myApp.controller("welcomeContoller", function($scope, productCountFactory) {
$scope.productCountFactory = productCountFactory;
});
Watch the property of the object.
{{productCountFactory.totalProducts}}
The DEMO on PLNKR.
By putting a reference on scope, on every digest cycle the watcher looks up the value of the property and updates the DOM if there is a change.
The totalProductCnt from your welcomeController isn't updated because it is assigned only once when the controller is created.
You can use several solutions to refresh the displayed value. Use a getter for your totalProducts in the factory :
myApp.factory("productCountFactory", function() {
var totalProducts = 0;
return {
getTotalProducts: function() {
return totalProducts;
},
addProduct: function() {
totalProducts++;
},
removeProduct: function() {
totalProducts--;
}
};
});
myApp.controller("welcomeContoller", function($scope, productCountFactory) {
$scope.getTotalProducts = productCountFactory.getTotalProducts;
});
myApp.controller("productController", function($scope, productCountFactory) {
$scope.addProduct = function() {
productCountFactory.addProduct();
};
$scope.removeProduct = function() {
if (productCountFactory.getTotalProducts() >= 1)
productCountFactory.removeProduct();
};
});
And update the view accordingly:
<div ng-controller="welcomeContoller">
{{getTotalProducts()}}
</div>
Plunkr Link

Determine controllerAs Syntax from the Controller

The ng-controller directive has two ways of instantiating a controller. Vanilla and controller as syntax. How can a controller determine which way it was invoked and adjust its behavior accordingly?
For example:
<div ng-controller="myController" >
<p> {{message}} World </p>
</div>
<div ng-controller="myController as myVm">
<p> {{myVm.message}} World </p>
</div>
<div ng-controller="myController as otherVm">
<p> {{otherVm.message}} World </p>
</div>
How can I make this work in my controller?
angular.module("myApp").controller("myController", function($scope) {
function usesClassSyntax() {
//what do i put here?
return true/false
};
if (usesClassSyntax()) {
var vm = this;
} else {
var vm = $scope;
};
vm.message = "Hello";
});
by using controller as syntax we just create a new variable in our scope..
angular.module("myApp").controller("myController", function($scope) {
function usesClassSyntax() {
//i think this will help
if (typeof $scope.myVm != 'undefined')
return true;
else
return false
};
if (usesClassSyntax()) {
var vm = this;
} else {
var vm = $scope;
};
vm.message = "Hello";
});

AngularJS - How to use the value recipe as a global variable?

I'm trying to figure out how to set a variable and use it globally. By globally i mean just outside the ng-controller scope.
The behavior is very simple. When the "gotologin" div is clicked, the login form must show up. same thing goes for register section.
But it seems the variables I used in ng-show directive are different from the one I've defined using .value and the controller. They all must be the same.
<div class="choose-box" ng-controller="mainController as mcontrol">
<div class="gotologin" ng-click="mcontrol.gotologin()">Login</div>
<div class="gotoregister" ng-click="mcontrol.gotoregister()">Register</div>
</div>
<div class="login-form" ng-show="loginclicked === true">
...
</div>
<div class="register-form" ng-show="registerclicked === true">
...
</div>
<script>
var app = angular.module('myapp', ['ngRoute']);
app.value("loginclicked" , false);
app.value("registerclicked" , false);
app.controller('mainController', function(loginclicked,registerclicked){
this.gotologin = function (){
loginclicked = true;
};
this.gotoregister = function (){
registerclicked = true;
};
});
</script>
You should set the values in the scope like:
$scope.loginclicked = false;
....
$scope.gotologin = function (){
$scope.loginclicked = true;
};
Edit:
Or try to broadcast an event with the value you need and in the other controller listen for that event.
You need to inject app values into your controller like a dependency.
I would do it as follows:
var app = angular.module('myapp', ['ngRoute']);
app.value('loginInfo', {
loginclicked: false,
registerclicked: false
});
app.controller('mainController', mainController);
mainController.$inject = ['$scope', loginInfo];
function mainController($scope,loginInfo){
$scope.loginInfo = loginInfo;
this.gotologin = function (){
$scope.loginInfo.loginclicked = true;
};
this.gotoregister = function (){
$scope.loginInfo.registerclicked = true;
};
}
Html will be <div ng-show="loginInfo.registerclicked"> and <div ng-show="loginInfo.loginclicked">

How to update value in one controller if the value is updated in different controller?

I have a page design in which i have attached the main controller to body:
<body ng-controller="firstController">
first
second
<input ng-model="hello" ng-disabled="xyz()">
<button id="test" ng-disabled="xyz()">test button</button>
{{hello}}
<div ng-view></div>
</body>
I load a template for default as
var mainApp = angular.module('mainApp',['ngRoute'])
.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/',{
templateUrl: 'partials/first.html',
controller: 'firstTemplate'
})
I my template i a check box as:
<div>
<input type="checkbox" ng-model="check">
</div>
Now i want the button #id to be disable the check box is unchecked, now i thought of using factory as these two are in different controllers:
mainApp.factory('clientId',function(){
var flag = true;
return flag;
});
mainApp.controller('firstController',['$scope','clientId',function($scope,clientId){
//$scope.check = true;
clientId.flag = false;
$scope.xyz = function(){
if(clientId){
return true;
}else{
return false;
}
}
}])
I am able to get the value from factory, now i want to update the value of the flag from different controller(template controller) and the value should reflect in first controller too so that the state of button can be updated.
mainApp.controller('firstTemplate',['$scope','clientId',function($scope,clientId){
}])
How can i update the value from second controller and make it reflect in first controller. If it is not possible is there and alternative to achieve this?
You can solve this using two ways.
1. using $rootScope.
2. using services.
using $rootScope:
<input ng-model="hello" ng-disabled="flagtoDisable">
<button id="test" ng-disabled="flagtoDisable">test button</button>
{{hello}}
<div ng-view></div>
mainApp.controller('firstController', ['$scope','$rootScope','clientId',function($scope,$rootScope,clientId){
//$scope.check = true;
clientId.flag = false;
$scope.xyz = function(){
if(clientId){
return true;
}else{
return false;
}
}
}])
mainApp.controller('firstTemplate','$scope','$rootScope','clientId',
function($scope,$rootScope,clientId){
$rootScope.flagtoDisable = false;
if($scope.check == true){
$rootScope.flagtoDisable = true;
}
}])
using Service:
mainApp.factory('clientId',function(){
var flag = {
status:false; };
return{
setFlag : funcion() {
flag.status = true;
}
getFlag : funcion() {
return flag;
}
});
mainApp.controller('firstController',['$scope','clientId',function($scope,clientId){
//$scope.check = true;
$scope.xyz = function(){
var flag = clientId.getFlag();
return flag.status;
}
}])
<input ng-model="hello" ng-disabled="xyz()">
<button id="test" ng-disabled="xyz()">test button</button>
{{hello}}
<div ng-view></div>
mainApp.controller('firstTemplate',['$scope','clientId',function($scope,clientId){
if($scope.check== true){
clientId.setFlag();
}
}])
This code is not tested.you can follow this approaches.
Yes, You can do it by using $rootScope
The ways are.
Initialize the $rootScope in your controller
Call the first controller scope variable from second controller
if 1st controller varaiable is $scope.name
now you just call $rootScope instead of $scope in second controller
like
$rootScope.name

Resources