updating $scope value on $rootScope.$on doesnt update DOM (UI) [duplicate] - angularjs

I'm trying to making some custom elements with AngularJS's and bind some events to it, then I notice $scope.var won't update UI when used in a binding function.
Here is a simplified example that describing the probelm:
HTML:
<!doctype html>
<html ng-app="test">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="Ctrl2">
<span>{{result}}</span>
<br />
<button ng-click="a()">A</button>
<button my-button>B</button>
</div>
</body>
</html>
JS:
function Ctrl2($scope) {
$scope.result = 'Click Button to change this string';
$scope.a = function (e) {
$scope.result = 'A';
}
$scope.b = function (e) {
$scope.result = 'B';
}
}
var mod = angular.module('test', []);
mod.directive('myButton', function () {
return function (scope, element, attrs) {
//change scope.result from here works
//But not in bind functions
//scope.result = 'B';
element.bind('click', scope.b);
}
});
DEMO : http://plnkr.co/edit/g3S56xez6Q90mjbFogkL?p=preview
Basicly, I bind click event to my-button and want to change $scope.result when user clicked button B (similar to ng-click:a() on button A). But the view won't update to the new $scope.result if I do this way.
What did I do wrong? Thanks.

Event handlers are called "outside" Angular, so although your $scope properties will be updated, the view will not update because Angular doesn't know about these changes.
Call $scope.$apply() at the bottom of your event handler. This will cause a digest cycle to run, and Angular will notice the changes you made to the $scope (because of the $watches that Angular set up due to using {{ ... }} in your HTML) and update the view.

This might be also a result of different problem but with the same symptoms.
If you destroy a parent scope of the one that is assigned to the view, its changes will not affect the view in any way even after $apply() call. See the example - you can change the view value through the text input, but when you click Destroy parent scope!, model is not updated anymore.
I do not consider this as a bug. It is rather result of too hacky code in application :-)
I faced this problem when using Angular Bootstrap's modal. I tried to open second modal with scope of the first one. Then, I immediately closed the first modal which caused the parent scope to be destroyed.

use timeout
$timeout(function () {
code....
},
0);

Related

How to change value of scope within a function - Why is my code not working?

Simple ng-class binding is not triggered when called inside a function, how can I resolve this?
$scope.afterHide = function() {
$scope.inputState = "fade-in";
}
<label ng-class="inputState">Next statement</label>
Works fine in this example:
angular.module("app",[])
.controller("ctrl", function($scope) {
$scope.afterHide = function() {
$scope.inputState = "fade-in";
};
$scope.reset = function() {
$scope.inputState = "";
};
});
.fade-in {
background-color: red;
}
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
<label ng-class="inputState">Next statement</label>
<br><button ng-click="afterHide()">Invoke afterHide</button><br>
<button ng-click="reset()">Reset</button>
</div>
If it works then I think it has something to do with the overall logic of my code. The function $scope.afterHide is triggered by an event on one of the directives, this directive is defined outside the controller. In html its basically just another div that has a state of change. When a change happens, other elements on the page will also be affected, in this context, that other element is the label tag. When the change happens, the $scope.afterHide function within the controller is called by the directive which is defined outside of the controller.
Scopes are arranged in hierarchical structure which mimic the DOM structure of the application.
The ng-click directive cannot invoke a function on a scope that is outside its hierachy. Also if the ng-click directive is on a template inside a directive that uses isolate scope, the event must be connected to parent scope with expression, "&", binding.
For more infomation, see
AngularJS Developer Guide - Scopes
AngularJS Developer Guide - Directives (Isolating a Scope)

How does AngularJS respond to a form value being updated in Javascript?

I don't use Angular regularly, but I understand that one of the key features is that when data is updated on a form element, it is automatically updated in the model.
If you are instead using a library like jQuery, you must manually attach an event to the form input that updates the model when it is changed, as in $('#myInput').on('change', updateModel);
Although the above handler will be fired when myInput is changed by the user, it will not be fired if myInput is changed by Javascript code such as $('#myInput').val('hello world');
My question is, how does Angular know when a form input is changed in Javascript code?
Angular applies a scope digest every time it's needed (by an Angular function) during which it checks the states of all the scope variables, including the models used, of course.
If you modify some of those variables manually, using JavaScript, jQuery, etc... Angular will not know that the changes have occured and you need to tell it so either by doing $scope.$apply() or by wrapping the code block in a $timeout callback (these are the most commonly used methods).
If you don't do it manually, you'd have to wait for some (if any) other Angular event to trigger the digest cycle, which is never good.
See this example, note how nothing happens when you just update the value, but you need to do it manually (ng-click does it) in order for DOM to update:
angular.module('app', [])
.controller('Ctrl', function($scope){
$scope.ourValue = 'Initial Value';
window.exposedFunc = function(v, digest) {
$scope.ourValue = v;
if (digest) {
$scope.$apply();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
<button onclick="exposedFunc('First Button Value')">Update Value - No Digest</button>
<button onclick="exposedFunc('Second Button Value', true)">Update Value - Force Digest</button>
<button ng-click="">Force Digest only</button>
<p>{{ourValue}}</p>
</div>
Here's a super simple example of binding using keyup event. It should be enough to get you started on your projects:
var res = document.getElementById('r');
function handleChange(v) {
res.textContent = v;
}
<input onkeyup="handleChange(this.value)" type="text" value="Initial value" />
<p id="r">No binding yet</p>

Finished Loading of ng-include in angular js

What is the best way to detect the end of html loading by ng–include? I want to write some code that runs when it has finished loading.
There are two ways to detect when ng-include finished loading, depending on your need:
1) via onload attribute - for inline expressions. Ex:
<div ng-include="'template.html'" onload="loaded = true"></div>
2) via an event $includeContentLoaded that ng-include emits - for app-wide handling. Ex:
app.run(function($rootScope){
$rootScope.$on("$includeContentLoaded", function(event, templateName){
//...
});
});
when it finishes loading the content
you can use onload for it as below
<div ng-include=".." onload="finishLoading()"></div>
in controller,
$scope.finishLoading = function() {
}
after loading the ng-include finishLoading scope function will call.
here is the working Demo Plunker
You can use this code:
$scope.$on('$includeContentLoaded', function () {
// it has loaded!
});
Here's a complete example that will catch all the ng-include load events emitted by the application:
<html ng-app="myApp">
<head>
<script src="angular.min.js"></script>
</head>
<body ng-controller="myController">
<div ng-include="'snippet.html'"></div>
<script>
var myApp = angular.module("myApp",[]);
myApp.controller('myController', function($scope) {
$scope.$on('$includeContentLoaded', function(event, target){
console.log(event); //this $includeContentLoaded event object
console.log(target); //path to the included resource, 'snippet.html' in this case
});
});
</script>
</body>
</html>
A problem I had, and the reason I take the time to post this, is I failed to include both the ng-app and ng-controller in my HTML markup.
If I have to wait for the element to be present, I wrap a $timeout with $includeContentLoaded:
var selector = '#foo';
$rootScope.$on('$includeContentLoaded', function(event, templateName){
$timeout(() => {
const $el = angular.element(selector);
if ($el.length) {
// Do stuff with element.
}
});
});
The timeout gives it time load properly, specially if the ng-include contains a directive that takes a few milliseconds to render.
There is an alternative for that only using JS call stack tricks. put ng-init="eventName" on the desired element. After that, declare the event on the angular controller:
$scope.eventName = () => {
setTimeout(() => { alert('loaded!'); }, 0);
}
That makes the alert only pop up when everything about angular is loaded, that occur because of the call-stack of JavaScript that considers some codes as Microtasks and some others as Macrotasks and they have priorities like the Microtasks run always first and just after all Microtasks run, the Macrotasks can take the place on the call-stack.
And, setTimeout() is considered a Macrotask for JavaScript, so it will only run as the latest tasks.

How does AngularJS encode the ngClick calls to a controller?

Here's a brief example here: http://plnkr.co/edit/x1sSw8?p=preview.
This is the HTML file:
<body ng-controller="MainCtrl as main">
<p>Hello {{main.name}}!
My current value for <code>main.value</code> is {{main.value}}.</p>
<button ng-click="main.doSomething()">Click Me</button>
</body>
Here is the app.js file:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function() {
this.name = 'World';
this.value = 0;
this.doSomething = function(){
this.value += 5;
}
this.doSomethingElse = function(){
this.value -= 5;
}
});
When I click the button, I normally expect the counter to go up in increments of 5. When I inspect the button and change the ng-click function to doSomethingElse(), why does it still continue to increment?
I understand I'm not directly changing the event listeners, so I wonder how AngularJS is protecting the controllers from outside tampering (like in the example I described). My guess is that it builds event listeners up after it parses the DOM for the first time (reading ng-click attributes and all).
When I inspect the button and change the ng-click function to doSomethingElse(), why does it still continue to increment?
You should check out the compilation & linking processes in Angular. The short reason is that, angular goes over these elements once they are created, not every time you click it. Since it is scanned and parsed by angular when the element is created, manually changing it by hand does not change anything, because angular does not check out what's written in there.
More info: https://docs.angularjs.org/guide/compiler

AngularJS event for when model binding or ng-repeat is complete?

We have a large model and it takes a couple seconds for ng-repeat to bind all the items in the model to the form. We would like to show a spinner while it this is happening. Is there some event that fires when binding is complete so we know when to hide the spinner?
Plunkr: http://plnkr.co/edit/GzzTW4?p=preview
Use ng-show on the spinner If you are using 1.2 use ng-if
<div ng-controller="Ctrl">
<div ng-show="complete">Complete={{complete}}</div>
<div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
thing {{thing}}
</div>
</div>
In your directive use $last to determine if rendering is done and then change the variable that you have the ng-show/ngif defined on.
function Ctrl($scope) {
$scope.complete=false;
$scope.doComplete = function() {
$scope.complete = true;
}
$scope.things = [
'A', 'B', 'C'
];
}
angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
return function(scope, element, attrs) {
if (scope.$last) {
scope.$eval('doComplete()');
}
};
});
You can watch for $last item compile/link function, and fire a custom event to the scope
In that kind of situations, I use the $timeout service mixed with the $viewContentLoaded event fired by angular ui router (if you use ui router) :
about $timeout :
This service is just a simple decorator for $timeout service that adds a "flush" and "verifyNoPendingTasks" methods.
about $viewContentLoaded
fired once the view is loaded, after the DOM is rendered. The '$scope' of the view emits the event.
My personal usecase is for a paymentForm to dynamically generate its hidden inputs (using HTML data computed serverside that I insert through ng-bind-html) and submit to the payment Gateway :
$scope.$on('$viewContentLoaded', function() {
$timeout(function () {
$scope.paymentForm.submit();
});
});
FYI in the above code example, .submit() is a function from a custom directive used with the form in order to be able to autosubmit the form.
Julien
For this I normally create a spinner div in your view with an ng-show="submitting". Then when the data is loaded, you set the $scope.submitting to 'false' show the spinner is hidden.
<!-- In your HTML -->
<div class="spinner" ng-show="submitting">
<div ng-repeat="p in people">
{{p.name}}
</div>
//In Javascript
$scope.submitting = true;
$scope.load_data = function(){
$http.get('/api/route')
.then(function(success){
$scope.submitting = false;
},function(error){
console.log(error);
});
}
I hope that helps

Resources