changing $rootScope inside angular ui-bootstrap modal controller - angularjs

I have problem trying to change $rootScope inside modal controller, The rootscope change but not immediately reflect in the view until i refresh page.
here is my code:
.controller('LoginController',function($scope,$rootScope,$modalInstance){
$scope.close = function(){
$rootScope.authentication = true;
}
});
and the code to open modal in other controller:
controller('myCtrl',function($scope,$modal){
$scope.openLoginModal = function(){
$scope.loginMdl= $modal.open({
templateUrl:'myview/myloginform.html',
controller:'LoginController'
});
$scope.loginMdl.result.then(
function(){},
function(){}
);
}
});
Finally, the simple HTML to open login modal;
<div ng-controller='myCtrl'>
<button ng-click='openLoginModal()'>Login </button>
</div>
<div>
<p ng-show='authentication'> USER HAS LOGGED IN</p>
</div>
as you can see, I have change the "authentication" var of $rootScope, but the change is not reflected immediately in the html view.
Could have some advise pls.

try
$rootScope.$apply();
to get the the change in rootscope applied you have to use the above code.

Related

Not update scope immediately, watchers dont work at modal windows using ngDialog angular js

I am using ngDialog module for angularjs. My problem is that when I make a action at modal windows, I hope that my interface change depending of scope changes, but ng-if or ng-show or simply print variable not update. If I print in console I can see the rules values, but the interface not update.
My Code:
controller:
export class NewEntityController {
constructor($scope, $routeParams, $location, ngDialog) {
"ngInject";
// initialize scope
$scope.ruleForm = false;
$scope.rules = [];
$scope.showRulesSetting = function()
{
ngDialog.open({ template: 'views/modal-windows/rules.html', className: 'ngdialog-theme-default', scope: $scope });
};
$scope.addRule = function()
{
$scope.rules.push('rule-'+new Date().getTime());
console.log($scope.rules);
}
}}
Normal Page View:
<span style="color: blue;" ng-click="showRulesSetting()"><i class="fa fa-cog" aria-hidden="true"></i> Advance rules</span>
Modal Windows View:
<div>
<button ng-click="addRule()">Add</button>
</div>
<div id="ruleslist" ng-if="rules.length > 0">
{{rules}}
</div>
When I click in "Add" button I can see rules value in console, but in interface div with id="ruleslits" never show and the result of {{rules}} is always []. I test with $scope.$apply() but whithout result.

Angular Modal is not working properly

I am using Angular bootsrap modal service. version of ui-bootstrap is angular-ui-bootstrap 1.3.3. below is my code.
First on module , I have registered correctly.
var angularFormsApp = angular.module("angularFormsApp", ["ngRoute", "ui.bootstrap"]);
then on angular controller , I have injected this directive correctly.
var loginController = function ($scope, $window, $routeParams, $uibModal, DataService)
then I am calling this modal by following code inside same controller
var onError = function (reason) {
$scope.modalOptions.headerText = "Error";
$scope.modalOptions.bodyText = reason.statusText;
$uibModal.open({
templateUrl: baseurl + 'app/ErrorMessages/PopUpErrorMessage.html',
controller: 'loginController'
});
};
$scope.cancelForm = function () {
$uibModalInstance.dismiss('cancel');
};
Now as you can see I have created separate html file for modal and below is html
<div class="modal-header">
<h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
<p>{{modalOptions.bodyText}}</p>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" value="Close"
ng-click="cancelForm()" />
</div>
Now till here everything is working , I mean on error method , modal is showing but problem is its showing blank , even nothing happening on close button click.
There is no error in console of chrome browser. Here is screen shot.
Your Modal does not know about your controller's scope. Try changing to this:
$uibModal.open({
templateUrl: baseurl + 'app/ErrorMessages/PopUpErrorMessage.html',
scope: $scope
});
To use your current controller variables try to change
controller: 'loginController' to scope: $scope. It will pass current scope to the modal.
Similar problem was here: AngularJS passing data to bootstrap modal

$rootScope changed doesn't reflect on template

I'm a newbie in angularjs. I'm trying to build a simple app which contain login page and dashbboard page.
Now, I got a problem with updating html template when rootScope changed.
Here is my component template :
<!-- show dashboard page app >
<div layout="column">
<div ng-show="$rootScope.isAuthenticated">
<pm-header></pm-header>
<div layout="row">
<pm-sidebar></pm-sidebar>
<div layout="column" class="sitecontent" layout-padding>
<md-content ui-view></md-content>
</div>
</div>
</div>
<!-- show login page app >
<div ng-hide="$rootScope.isAuthenticated">
<pm-homeheader></pm-homeheader>
<div layout="row">
<md-content ui-view flex></md-content>
</div>
</div>
</div>
Login blockcodes :
'use strict'
export default ['$rootScope', '$state', '$http', '$window', function($rootScope, $state, $http, $window) {
this.user = {};
this.login = () => {
$http.post('./api/auth/login', this.user)
.success(function(data, status, headers, config) {
$window.sessionStorage.token = data.token;
$rootScope.user = data.user;
$rootScope.isAuthenticated = true;
$state.go('home');
})
.error(function(data, status, headers, config) {
delete $window.sessionStorage.token;
})
};
}]
My problem is when I logged and go back to home state, the ui-router updated the template to ui-view, but the ng-show="$rootScope.isAuthenticated" didn't reflect the changes on html, it show the block codes of home page instead of dashboard page.
Can anyone help me for this case, many thanks.
Use:
ng-show="$root.isAuthenticated"
You can't access $rootScope in the template, when you access it in a controller you inject it in. $root works because when angular creates a rootScope it sets a reference to $root to itself so its just like accessing any other property on the scope.
Refer to AngularJS rootScope code Line 135: https://github.com/angular/angular.js/blob/v1.3.6/src/ng/rootScope.js#L135
You should not use either $scope OR $rootScope while using variable for binding on HTML, so as soon as variable update in $rootScope, isAuthenticated will be taken from $rootScope while evaluating value of ng-show.
ng-show="isAuthenticated"
Though directly using $rootScope, wouldn't consider as a good practice. I'd suggest you to create a service/factory with a name userService that will have shareable user information among-st angular components.

AngularJS Populating input field with directive but not captured in $scope

When I populate an input field from within a directive, it shows on the DOM, but $scope is not capturing the value. How do I fix it so that $scope captures the new info?
How to reproduce the behaviour from my Fiddle:
Click Fill with Directive
Click Log
--> $scope.input val is undefined
Fill input with 'asdf'
Click Log
--> $scope.input val is 'asdf'
Fill input with 'abcd'
Click Fill with Directive
--> DOM shows 'quick brown fox'
Click Log
--> $scope.input val is 'abcd'
My code is here: JSFiddle
JS:
'use strict';
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.logResult = function(){
console.log($scope.input);
}
});
app.directive('fillInput', function(){
return {
link: function($scope, elem){
$scope.fillFormDirective = function() {
console.log(elem);
elem.val('quick brown fox');
}
}
};
});
HTML:
<div ng-controller='myCtrl'>
<div>
<input type="text" ng-model="input.weird" id="inputField" fill-input />
</div>
<div>
<button ng-click="fillFormDirective()" >Fill With Directive</button>
</div>
<div>
<button ng-click="logResult()">Log Result</button>
</div>
</div>
There is a problem with the code you posted:
In your link function your scope should be scope NOT $scope.
If you want 2 way binding between you controller and the directive, you need to pass in a variable through an isolate scope. However with an isolate scope the fillFormDirective() method won't be called if it is declared on elements that don't have the fill-input directive on them.
Try this:
app.directive('fillInput', function(){
return {
scope:{
fillInput:'='
}
link: function(scope, elem){
elem.val(scope.fillInput);
elem.bind("click", function(e){
console.log(elem);
elem.val('quick brown fox');
});
}
};
});
And your HTML:
<input type="button" fill-input="text" />
See working plunk.
EDIT I've updated the plunk to not make use of an isolate scope.
Solution from this SO thread:
Update Angular model after setting input value with jQuery
Working Plunkr:
http://plnkr.co/edit/QKDaHT3CllyBtrRPdYUr?p=preview
Basically, quoting #Stewie,
ngModel listens for "input" event, so to "fix" your code you'd need to trigger that event after setting the value:
elem.bind("click", function(e){
console.log(elem);
newElem.val('quick brown fox');
newElem.triggerHandler('input'); <-----This line of code fixed the problem
});

How to use angular to refresh a div?

when I click the "Refresh" or the src,I want to only refresh the following "div" and another div ,not the whole html.
How do use angularjs to do?
<div>
<img alt="Refresh" src="/Captcha/[[.CaptchaId]]/" /><span>Refresh</span>
</div>
Thanks!
You bind your img src to your scope and add a ng-click handler to your img tag to handle click event, and change the binded value accordingly
angular.module("myApp", [])
.controller("MainCtrl", function ($scope) {
$scope.url = "old.png";
$scope.refresh = function() {
$scope.url = "new.png";
};
})
and your html:
<img src="{{url}}" ng-click="refresh()">Refresh</img>
You can try to prevent default handler:
html:
<img src="{{url}}" ng-click="saveUser($event)">Refresh</img>
js:
$scope.saveUser = function (event) {
event.preventDefault();
// your code
}

Resources