I do this in Ionic Framework. It started in the home.html template with eventmenu.home state. The $scope.aaa variable is 10 and it shows that value correctly. However, in a child controller TestCtrl of that template, I cannot change the $scope.aaa value and gets it updated. What's wrong with my method as why aaa did not get increased? Is TestCtrl in a different scope than HomeCtrl although it should be the child of HomeCtrl, no?
CODE:
http://codepen.io/hawkphil/pen/xbmZGm
HTML:
<script id="templates/home.html" type="text/ng-template">
<ion-view view-title="Welcome" >
<ion-content class="padding" >
<p>Swipe to the right to reveal the left menu.</p>
<p>(On desktop click and drag from left to right)</p>
<p>{{ aaa }}</p>
<div ng-controller="TestCtrl">
<a ng-click="clickMe()" href="">Click Me</a>
</div>
</ion-content>
</ion-view>
</script>
JS:
.controller('HomeCtrl', function($scope) {
$scope.aaa = 10;
})
.controller('TestCtrl', function($scope) {
$scope.clickMe = function() {
$scope.aaa++;
}
})
p.s I am using the code from somebody so please ignore other stuffs.
This isn't an issue with Ionic, or with ui-router, or really even with Angular. It's just how javascript works.
You can see the same issues arise in plain Angular using ng-if. It has to do with how javascript inheritance works.
If the child scope doesn't have it's own aaa property it uses it's parent. But once you click the button, you make it's own property, one more than the parent's was. But now they are separate properties, the parent's aaa and the child's aaa.
Example
You can see a pure javascript example here...
Example. Click the Inc Parent as much as you like, both the parent and child displays are incremented. Clicking the Inc Child breaks the connection. Once the connection is broken you can "unhide" the parent value by deleting the child's property by clicking the Unhide button.
code
var obj = function () {}
obj.aaa = 10
obj.inc = function () {
this.aaa += 1;
};
var objB = function () {};
objB.__proto__ = obj; // Make objB a child of obj
objB.inc = function () {
this.aaa += 1;
};
objB.unhide = function () {
delete this.aaa;
};
var update = function () {
document.getElementById("p").textContent = obj.aaa;
document.getElementById("c").textContent = objB.aaa;
};
update();
html
<button onclick="obj.inc(); update();">Inc Parent</button>
<button onclick="objB.inc(); update();">Inc Child</button>
<button onclick="objB.unhide(); update();">Unhide</button>
<p>
Parent's value: <span id="p"></p>
</p>
<p>
Child's value: <span id="c"></p>
</p>
Every controller has its own $scope object. Child controllers can access their parents using $parent:
.controller('TestCtrl', function($scope) {
$scope.clickMe = function() {
$scope.$parent.aaa++;
}
})
codepen
Related
So I have this inside my controller:
var myApp = angular.module('app', [], function ($interpolateProvider) {
$interpolateProvider.startSymbol('[%');
$interpolateProvider.endSymbol('%]');
});
myApp.controller('MyController', function ($scope) {
$scope.show = [];
// confirmed this returns true when intended
$scope.showElement = function (id) {
return ($scope.show.indexOf(id) > -1);
};
});
And my HTML structured as below, with my-class using display: none; and other rules which are imperative to the display of this element. Because of the number of instances where it is being used I cannot simply remove the class or alter its rules. In all other instances in the application, this works as expected.
<div class="my-class" ng-show="showElement(obj.id)">
...
</div>
The element is not shown on page load, nor is its appearance updated if the underlying variable $scope.show is changed.
The previous development team was manually (by using deep and obfuscated Javascript) adding an additional CSS class in the other instances where it was being used.
My solution was to add a visible class using the ng-class directive:
<div class="my-class" ng-class="{'visible': showElement(obj.id)}">
....
</div>
I'm working on a site, and I started building it before I realized I needed some dynamic framework. After learning about AngularJS, I decided to use it, where I needed (not the whole site).
I have a very long script in JS, and I want to be able to get and set the variables from within AngularJS directives and controllers.
I found this answer, and it was quite good - I was able to get the variable from within the function. But when the variable changed outside the function, AngularJS' variable won't update.
My code looked something like this:
JS:
var app = angular.module('someName', []);
var currentPage = 'Menu';
app.controller('PageController', ['$window','$scope', function($window,$scope){
this.currentPage = $window.currentPage;
this.isPage = function(page){
return (page == this.currentPage);
};
}]);
function button1onClick(){
currentPage = 'Game';
}
HTML:
<div ng-controller="PageController">
<div id="Game" ng-show="page.isPage('Game')">
...
</div>
<div id="Menu" ng-show="page.isPage('Menu')">
...
</div>
</div>
(button1onClick was called when I clicked some button on the page)
The idea is that I have two dives I want to switch between, using a globle variable. 'Menu' page was visible at first but upon clicking I was supposed to see only the 'Game' div.
The variable inside the controller didn't upadte, but was only given the initial value of currentPage.
I decided to use the $window service inside the isPage function, but this didn't work either. Only when I called a function that tested the $window.currentPage variable, the pages switched - like I wanted:
JS:
var app = angular.module('someName', []);
var currentPage = 'Menu';
app.controller('PageController', ['$window','$scope', function($window,$scope){
this.isPage = function(page){
return (page == $window.currentPage);
};
this.button2onClick = function() {
$window.alert($window.currentPage);
}
}]);
function button1onClick(){
currentPage = 'Game';
}
HTML:
<button onclick="button1onClick()">CLICK ME</button> //Button 1
<div ng-controller="PageController">
<button ng-click="page.button2onClick">CLICK ME</button> //Button 2
<div id="Game" ng-show="page.isPage('Game')">
...
</div>
<div id="Menu" ng-show="page.isPage('Menu')">
...
</div>
</div>
So the only way I was able to update the pages is to call a function that tests the variable, thus updating the variable in AngularJS.
Is there a way to access a global variable without needing to test it to update it?
Am I doing something wrong? I don't want to convert my whole site to AngularJS-style, I like the code the way it is. Is AngularJS not the framework for me?
EDIT:
some things to clear out:
I'm new to AngularJS, so if you could explain what your answer does it would be great.
The whole reason why I do this instead of redirecting to another page is not to shut down socket.io 's connection
OP, take a look at UI Router.
var app = angular.module("app", ['ui.router']);
app.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/main');
$stateProvider.state('main', {
controller: 'MainCtrl',
templateUrl: 'main.html',
url: '/main/'
}).state('game', {
controller: 'GameCtrl',
url: '/game/',
templateUrl: 'game.html'
});
}]);
HTML links:
<a ui-sref="main">Go to Main</a>
<a ui-sref="game">Go to Game</a>
View injection
<div ui-view="">
</div>
You should not use $window as a map object.
You should probably create a PageService:
angular.module('someName')
.factory('Page', [function(){
var currentPage = 'Menu';
return {
getPage: function() {
return currentPage;
},
isPage: function(page) {
return page === currentPage;
},
setPage: function(page) {
currentPage = page;
}
}
}]);
app.controller('PageController', ['Page','$scope', function(Page,$scope){
this.currentPage = Page.getPage();
this.isPage = Page.isPage;
this.button10Click = function(){
Page.setPage('Game');
}
}]);
HTML
<div class="button" ng-click="page.button10Click()">Game</div>
After reading malix's answer and KKKKKKKK's answer, and after researching a bit, I was able to solve my problem, and even write a better looking code.
To switch divs as I wanted in the example, I used ui-router, almost exactly the way KKKKKKKK did. The only difference is that I change state programmaticly - $state.go('menu')
To access global variables in other places in my code, I had to re-structure my whole code to fit AngularJS's structure, and used a Service, similarly to malix's answer:
app.factory('Data', function(){
var Data = {};
//DEFINE DATA
Data.stateChange = function(){};
Data.menuData = {};
Data.randomColors = ['#35cd96', '#6bcbef', '#E8E1DA', '#91ab01'];
/RETURN DATA
return Data;
});
It can be done using $rootScope. Variable initialize once can be accessible in other controllers.
function Ctrl1($scope, $rootScope) {
$rootScope.GlobalJSVariableA= window.GlobalJSVariable; }
Any controller & any view can access it now
function CtrlN($scope, $rootScope) {
$scope.GlobalJSVariableA= $rootScope.GlobalJSVariableA;
}
inside view I'm conditionally rendering html using ng-include and ng-if
<div ng-controller="myController">
<div ng-if="myProperty == 1">
<div ng-include="'view1.html'"></div>
</div>
<div ng-if="myProperty == 2">
<div ng-include="'view2.html'"></div>
</div>
</div>
and inside controller I have $scope.myProperty which receive value inside controller using $scope injection from other js object. On this controller I have also callback function which updates $scope.myProperty every x seconds.
app.controller('myController', function ($scope) {
...
$scope.myProperty = 0; //init value
function callback() {
$scope.$apply(); // force update view
// correctly write myProperty value on every data change
console.log($scope.myProperty);
}
var otherJsObject= new myObject($scope, callback);
otherJsObject.work();
...
}
callback function correctly change myProperty value but it doesn't update inside view every time.
update:
$scope.bindUIProp = { a: $scope.myProperty};
function callback() {
$scope.$apply();
$scope.bindUIProp.a = $scope.myProperty;
console.log('Callback ' + $scope.myProperty);
console.log('drawstage ' + $scope.bindUIProp.a);
}
var otherJsObject= new myObject($scope, callback);
otherJsObject.work();
and inside view I used object property
<div ng-controller="myController">
<div ng-if="bindUIProp.a == 1">
<div ng-include="'view1.html'"></div>
</div>
<div ng-if="bindUIProp.a == 2">
<div ng-include="'view2.html'"></div>
</div>
</div>
this approach work every time when page is refreshed, parial view is not updated from view1 to view2 when scope.bindUIProp.a is changed to 2.
Instead of writing to property at root level. Write one level below.
Instead of $scope.myProperty,
use $scope.mp.myProperty
Both ng-if and ng-include create child scopes.
You are having problems due to using a primitive in your main scope. Primitives don't have inheritance so the binding is getting broken in the nested child scopes.
change it to an object:
$scope.myProperty = { someProp: 0};
Personally I rarely use ng-include because of the child scope it creates. I prefer having my own directive if all I want is to include a template.
Have an angular application. Using ui-select.
<div class="col-md-12" ng-controller="FlatController as flat">
<form ng-submit="flat.createFlat()">
<ui-select ng-model="flat.flatData.typelocal" theme="bootstrap">
<ui-select-match placeholder="Type" id="localtype">
{{ $select.selected.type }}
</ui-select-match>
<ui-select-choices repeat="uitypelocal.type as uitypelocal in flat.typelocal1 track by $index | filter: $select.search">
<div ng-bind-html="uitypelocal.type | highlight: $select.search"></div>
</ui-select-choices>
</ui-select>
<button class="btn btn-danger">Send</button>
</form>
</div>
In form i have some inputs and selects. Now, i want to have in the select data from another controller. How can i do it?
I have a service:
angular.module('flatService', [])
.factory('Flat', function($http){
var flatFactory = {};
flatFactory.allFlats = function(){
return $http.get('/api/flats');
};
flatFactory.create = function(flatData){
return $http.post('/api/addflat', flatData);
};
return flatFactory;
})
});
If you want to call one controller into another there are five methods available
$rootScope.$emit() and $rootScope.$broadcast()
If Second controller is child ,you can use Parent child communication .
Use Services
Kind of hack - with the help of angular.element()
inject '$controller'
1. $rootScope.$emit() and $rootScope.$broadcast()
Controller and its scope can get destroyed,
but the $rootScope remains across the application, that's why we are taking $rootScope because $rootScope is parent of all scopes .
If you are performing communication from parent to child and even child wants to communicate with its siblings, you can use $broadcast
If you are performing communication from child to parent ,no siblings invovled then you can use $rootScope.$emit
HTML
<body ng-app="myApp">
<div ng-controller="ParentCtrl" class="ng-scope">
// ParentCtrl
<div ng-controller="Sibling1" class="ng-scope">
// Sibling first controller
</div>
<div ng-controller="Sibling2" class="ng-scope">
// Sibling Second controller
<div ng-controller="Child" class="ng-scope">
// Child controller
</div>
</div>
</div>
</body>
Angularjs Code
var app = angular.module('myApp',[]);//We will use it throughout the example
app.controller('Child', function($rootScope) {
$rootScope.$emit('childEmit', 'Child calling parent');
$rootScope.$broadcast('siblingAndParent');
});
app.controller('Sibling1', function($rootScope) {
$rootScope.$on('childEmit', function(event, data) {
console.log(data + ' Inside Sibling one');
});
$rootScope.$on('siblingAndParent', function(event, data) {
console.log('broadcast from child in parent');
});
});
app.controller('Sibling2', function($rootScope) {
$rootScope.$on('childEmit', function(event, data) {
console.log(data + ' Inside Sibling two');
});
$rootScope.$on('siblingAndParent', function(event, data) {
console.log('broadcast from child in parent');
});
});
app.controller('ParentCtrl', function($rootScope) {
$rootScope.$on('childEmit', function(event, data) {
console.log(data + ' Inside parent controller');
});
$rootScope.$on('siblingAndParent', function(event, data) {
console.log('broadcast from child in parent');
});
});
In above code console of $emit 'childEmit' will not call inside child siblings and It will call inside only parent, where $broadcast get called inside siblings and parent as well.This is the place where performance come into a action.$emit is preferrable, if you are using child to parent communication because it skips some dirty checks.
2. If Second controller is child, you can use Child Parent communication
Its one of the best method, If you want to do child parent communication where child wants to communicate with immediate parent then it would not need any kind $broadcast or $emit but if you want to do communication from parent to child then you have to use either service or $broadcast
For example HTML:-
<div ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl">
</div>
</div>
Angularjs
app.controller('ParentCtrl', function($scope) {
$scope.value='Its parent';
});
app.controller('ChildCtrl', function($scope) {
console.log($scope.value);
});
Whenever you are using child to parent communication, Angularjs will search for a variable inside child, If it is not present inside then it will choose to see the values inside parent controller.
3.Use Services
AngularJS supports the concepts of "Seperation of Concerns" using services architecture. Services are javascript functions and are responsible to do a specific tasks only.This makes them an individual entity which is maintainable and testable.Services used to inject using Dependency Injection mecahnism of Angularjs.
Angularjs code:
app.service('communicate',function(){
this.communicateValue='Hello';
});
app.controller('ParentCtrl',function(communicate){//Dependency Injection
console.log(communicate.communicateValue+" Parent World");
});
app.controller('ChildCtrl',function(communicate){//Dependency Injection
console.log(communicate.communicateValue+" Child World");
});
It will give output Hello Child World and Hello Parent World . According to Angular docs of services Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
4.Kind of hack - with the help of angular.element()
This method gets scope() from the element by its Id / unique class.angular.element() method returns element and scope() gives $scope variable of another variable using $scope variable of one controller inside another is not a good practice.
HTML:-
<div id='parent' ng-controller='ParentCtrl'>{{varParent}}
<span ng-click='getValueFromChild()'>Click to get ValueFormChild</span>
<div id='child' ng-controller='childCtrl'>{{varChild}}
<span ng-click='getValueFromParent()'>Click to get ValueFormParent </span>
</div>
</div>
Angularjs:-
app.controller('ParentCtrl',function($scope){
$scope.varParent="Hello Parent";
$scope.getValueFromChild=function(){
var childScope=angular.element('#child').scope();
console.log(childScope.varChild);
}
});
app.controller('CarentCtrl',function($scope){
$scope.varChild="Hello Child";
$scope.getValueFromParent=function(){
var parentScope=angular.element('#parent').scope();
console.log(parentScope.varParent);
}
});
In above code controllers are showing their own value on Html and when you will click on text you will get values in console accordingly.If you click on parent controllers span, browser will console value of child and viceversa.
5.inject '$controller'
You can inject '$controller' service in your parent controller(MessageCtrl) and then instantiate/inject the child controller(DateCtrl) using:
$scope.childController = $controller('childController', { $scope: $scope.$new() });
Now you can access data from your child controller by calling its methods as it is a service.
Let me know if any issue.
The view's scope is determine by it's controller. However, angular allows nested view scope inheritance, meaning that a view nested inside another view has access to the parent view's scope.. for example:
<div ng-controller="OuterCtrl">
<div ng-controller="InnerCtrl">
...
</div>
<div>
the inner div would have access to the InnerCtrl's scope as well as the OuterCtrl's scope, but the outer div would only have access to the OuterCtrl's scope.
If you need data shared between non-related controllers (those that are not related by nested views), then the data should be provided by a service that can be injected into the controllers like:
app.factory('service', function() {
...
return {
data: someData
};
});
app.controller('ctrl1', [... function(..., service) {
$scope.data = service.data;
}]);
app.controller('ctrl2', [... function(..., service) {
$scope.data = service.data;
}]);
use $broadcase or $emit event like:
app.controller('ctrl1', ['$scope', '$rootScope', function($scope, $rootScope) {
$rootScope.$on("CustomEvent", function($event, data){
alert(data);
})
}]);
app.controller('ctrl2', ['$scope', function($scope) {
$scope.$emit("CustomEvent", "SecondControllerValue");
}]);
The jsFiddle for this question can be found here: http://jsfiddle.net/Hsw9F/1/
JavaScript (console.log debug information available in the jsFiddle)
var app = angular.module('StackOverflow',[]);
function ParentController($scope) {
$scope.parentCounter = 5;
}
function ChildController($scope) {
$scope.childCounter = $scope.parentCounter;
$scope.increaseCounters = function() {
++$scope.parentCounter;
++$scope.childCounter;
};
}
In the example above I have a counter in the parent and the child controllers named parentCounter and childCounter respectively. I've also provided a function in the child controller named increaseCounters() that increases both counters by one.
Both of these counters are displayed on the page:
<div ng-app="StackOverflow">
<div ng-controller="ParentController">
Parent Counter: {{parentCounter}}<br />
<div ng-controller="ChildController">
Child Counter: {{childCounter}}<br />
<a href="javascript:void(0)"
ng-click="increaseCounters()">Increase Counters</a>
</div><!-- END ChildController -->
</div><!-- END ParentController -->
</div><!-- END StackOverflow app -->
The problem is that AngularJS doesn't seem to update the {{parentCounter}} on the page, and only updates the {{childCounter}} when the increase counters function is called. Is there anything I have overlooked?
++$scope.parentCounter; creates a child scope property with name parentCounter that hides/shadows the parent scope property of the same name.
Add console.log($scope); to your increaseCounters() function to see it.
One workaround: ++$scope.$parent.parentCounter;
The problem you are experiencing has to do with the way JavaScript prototypal inheritance works. I suggest reading What are the nuances of scope prototypal / prototypical inheritance in AngularJS? -- it has some nice pictures explaining what happens when primitives are created in child scopes.
Because the child controller gets a copy of the parent counter value. If you want to increase the parent controller counter value, you need to execute a function on the parent controller:
function ParentController($scope) {
$scope.parentCounter = 5;
$scope.increaseParent = function() {
++$scope.parentCounter;
};
}
function ChildController($scope) {
$scope.childCounter = $scope.parentCounter;
$scope.increaseCounters = function() {
console.log('-------------------------------------');
console.log('parent before: ' + $scope.parentCounter);
console.log('child before: ' + $scope.childCounter);
$scope.increaseParent();
++$scope.childCounter;
console.log('parent after: ' + $scope.parentCounter);
console.log('child after: ' + $scope.childCounter);
};
}