AngularJS UI Bootstrap dismiss() won´t work - angularjs

Let me start by saying that I am very new to angular.
I have tried to setup a modal ui which works fine. But when I click the "cancel" button on the interface nothing happens.
This is my code:
(function () {
var domainName = 'TournamentCategory';
angular.module('tournamentCategories').controller("CategoriesController",
['$scope', '$modal', 'guidGenerator', 'eventBus', domainName + "Service",
'TournamentCategoryModelFactory',
function ($scope, $modal, guidGenerator, eventBus, domainService, modelFactory)
{$scope.openTournamentTree = function () {
var modalInstance = $modal.open({
templateUrl: 'TournamentTreeModal.html',
controller: 'TreeController',
size: 'wide-90',
resolve: {
}
});
modalInstance.result.then(function (selectedItem) {
//$scope.selected = selectedItem;
}, function () {
//$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
}]);
})();
The HTML:
<script type="text/ng-template" id="TournamentTreeModal.html">
<div class="modal-header">
</div>
<div class="modal-body">
<div class="include-tree" ng-include="'tournament-tree.html'"></div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">GEM</button>
<button ng-click="cancel()" class="btn btn-warning" type="button" data-dismiss="modal">LUK, uden at gemme</button>
</div>
This is my "treeController"
angular.module('tournamentTree').controller("TreeController", ['$scope', 'guidGenerator', function ($scope, guidGenerator) {
$scope.allMatches = [];
$scope.finalMatch = [createNewMatch()];
$scope.tierCount = 1;
$scope.previousMatchTier = 0;
$scope.deletePreviousMatches = function (parentMatch) {
for (var i in parentMatch.previousMatches) {
var previousMatch = parentMatch.previousMatches[i];
_.remove($scope.allMatches, function (match) { return match.id == previousMatch.id });
}
parentMatch.previousMatches = [];
}
$scope.addMatches = function (thisMatch) {
if (thisMatch && !thisMatch.previousMatches)
thisMatch.previousMatches = [];
if (thisMatch && thisMatch.previousMatches.length == 0) {
thisMatch.previousMatches.push(createNewMatch(thisMatch));
thisMatch.previousMatches.push(createNewMatch(thisMatch));
}
}
$scope.addMatchTier = function () {
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
$scope.addMatches(match);
}
}
$scope.tierCount++;
}
$scope.previousMatchTier = function () {
for (var i in $scope.allMatches) {
var previous;
if (previous.allMatches.length == i) {
previous = $scope.allMatches[i] - $scope.allMatches[i - 1];
}
}
}
$scope.removeMatchTier = function () {
//if (confirm('Er du sikker på, at du vil slette det yderste niveau af turneringstræet?')) {
var matchesToDelete = [];
for (var i in $scope.allMatches) {
var match = $scope.allMatches[i];
if (match.previousMatches.length == 0) {
matchesToDelete.push(match.nextMatch);
//$scope.deletePreviousMatches(match.nextMatch);
}
}
for (var i in matchesToDelete) {
$scope.deletePreviousMatches(matchesToDelete[i]);
}
$scope.tierCount--;
//}
}
$scope.hasPreviousMatches = function (match) {
return match && match.previousMatches && match.previousMatches.length > 0;
}
$scope.moveWinnerToNextMatch = function (match, winnerName) {
match.nextMatch.setPlayerName(match.id, winnerName);
}
function createNewMatch(nextMatch) {
var newMatch = {};
newMatch.tier = nextMatch && nextMatch.tier ? nextMatch.tier + 1 : 1;
newMatch.id = guidGenerator.newGuid();
newMatch.player1 = "";
newMatch.player2 = "";
newMatch.nextMatch = nextMatch;
newMatch.previousMatches = [];
newMatch.setPlayerName = function(matchId, playerName) {
for (var i in newMatch.previousMatches)
{
if (newMatch.previousMatches[i].id == matchId)
{
if (i == 0)
newMatch.player1 = playerName;
else
newMatch.player2 = playerName;
}
}
}
$scope.allMatches.push(newMatch);
return newMatch;
}
}]);

$dismiss is already available on modal scope so in template raplace cancel() with $dimiss() http://angular-ui.github.io/bootstrap/#/modal

That needs to go in your modals controller 'TreeController'
angular.module('tournamentCategories').controller('TreeController', function($scope, $modalInstance) {
$scope.ok = function () {
modalInstance.close();
}
$scope.cancel = function () {
modalInstance.dismiss('cancel');
};
});
I have an example in this plunker

Related

Unable to get value from AngularJS Scope

I have an existing project in AngularJS. There is an HTML page with client address. Its markup is:
<div class="text-left m-t-lg">
<h5>
Address
</h5>
<address>
<div ng-show="customerInfo.companyName != ''"><small>{{customerInfo.companyName}}</small><br /></div>
<div ng-show="customerInfo.customerName != ''"><small>{{customerInfo.customerName}}</small><br /></div>
<div ng-show="customerInfo.address != ''"><small>{{customerInfo.address}}</small><br /></div>
<div ng-show="customerInfo.email != ''"><small>{{customerInfo.email}}</small></div>
</address>
</div>
The directive:
app.directive('addressHeader', function () {
return {
scope: {
addressHeaderInfo: '=info'
},
templateUrl: 'address/addressHeader.html',
controller: 'addressHeaderController',
controllerAs: 'ahc'
};
});
My issue is In addressHeaderController.js I don't see addressHeaderInfo or info or customerInfo object. I need to update this object. Where is this object initialized from? I don't know much about AngularJS.
Controller:
app.controller('addressHeaderController', ['$http', 'APIService', '$scope', '$stateParams', '$sessionStorage', '$translate', '$state', '$rootScope', '$timeout', '$locale', 'tmhDynamicLocale',
function ($http, APIService, $scope, $stateParams, $sessionStorage, $translate, $state, $rootScope, $timeout, $locale, tmhDynamicLocale) {
var ctl = this;
$scope.followingAddress = false;
$scope.followData = {};
$scope.issueDisplay = '';
$scope.showResend = true;
$scope.showLoyaltyColumn = $sessionStorage.userObject.clientInfo.showLoyaltyColumnOnSurveyDetail;
ctl.isOpen = false;
ctl.dateOptions = { showWeeks: false };
$scope.businessUnits = null;
$scope.targetDealership = null;
$scope.realignComment = null;
$scope.$watch('addressHeaderInfo', function () {
debugger;
//Where is $scope.addressHeaderInfo coming from?
if (typeof ($scope.addressHeaderInfo) != 'undefined') {
//Some operations here. Not related to assigning anything to $scope.
}
});
function getDepartmentData() {
//No assignment here as well.
}
$scope.resendData = function () {
if ($sessionStorage.clientObject.requiresResendJustification) {
$('#resendJustificationModal').modal('show');
}
else {
var resendData = {};
resendData.recordId = $scope.addressHeaderInfo.addressID;
resendData.statusId = 24;
APIService.postData(resendData, 'Address/UpdateResendStatus')
.then(function (data) {
if (data.status == 200) {
$rootScope.$broadcast('resendRequest');
}
else {
toastr["error"]('Error');
}
});
}
}
$scope.nextAddress = function () {
$rootScope.$broadcast('addressNavigation', $scope.AddressList[$scope.recordNumber]);
$scope.recordNumber = $scope.recordNumber + 1;
}
$scope.previousAddress = function () {
$rootScope.$broadcast('addressNavigation', $scope.AddressList[$scope.recordNumber-2]);
$scope.recordNumber = $scope.recordNumber - 1;
}
$scope.followAddress = function () {
APIService.postData($scope.addressHeaderInfo, 'Address/follow')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressFollowedSaved'));
$scope.followData = data.data;
$scope.followingAddress = true;
}
else {
toastr["error"]($translate.instant('AddressFollowedErrored'));
}
})
}
$scope.unfollowAddress = function () {
APIService.deleteData('Address/follow/' + $scope.followData.AddressFavoriteId)
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressUnfollowedSaved'));
$scope.followingAddress = false;
}
else if (data.status == 500) {
toastr["error"]($translate.instant('AddressUnfollowedErrored'));
}
});
}
$scope.AddressReminder = function () {
$('#setReminderPopup').modal('show');
}
$scope.saveReminder = function () {
$scope.followData.notificationDate = $scope.followData.displayDate;
APIService.postData($scope.followData, 'Address/follow/reminder')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressReminderSaved'));
$('#setReminderPopup').modal('hide');
}
else {
toastr["error"]($translate.instant('AddressReminderErrored'));
}
})
}
$scope.realignAddress = function () {
if ($scope.addressHeaderInfo) {
if (!$scope.businessUnits) {
getBusinessUnits();
}
var bu = $scope.addressHeaderInfo.businessUnit;
if (bu) {
bu.realignDisplayName = bu.name + ', ' + bu.shippingCity + ', ' + bu.suppliedBusinessUnitNumber;
}
$scope.realignComment = null;
$('#realignPopup').modal('show');
}
}
$scope.saveRealignRequest = function () {
var realignedAddress = $scope.addressHeaderInfo;
var realignData = {
AddressId: $scope.addressHeaderInfo.AddressID,
businessUnitId: $scope.targetDealership.businessUnitID,
notes: $scope.realignComment
};
APIService.postData(realignData, 'Address/requestRealignment')
.then(function (data) {
if (data.status == 200) {
toastr["success"]($translate.instant('AddressRealignRequestSaved'));
$('#realignPopup').modal('hide');
realignedAddress.realignmentStatus = 'Pending'; // cause Realign button to disappear and "Realignment is pending" message to show
} else {
toastr["error"]($translate.instant('AddressRealignRequestErrored'));
}
});
}
$scope.$on('advanceToNextIssue', function (event, data) {
if ($scope.AddressList && ($scope.recordNumber < $scope.AddressList.length)) {
$scope.nextAddress();
}
});
}]);

Scope from controller does not pass to directive

I have a html like this :
<div id="create-group" ng-controller="groupCreateController">
<div id="container">
<h1>Create group</h1>
<div class="row">
<div class="col-md-4"><input placeholder="Group Name.." ng-model="group.name"></div>
<div class="col-md-8">
<label>Group Description : </label>
<textarea ng-model="group.description"> </textarea>
</div>
</div>
<br/>
<div class="row">
<div class="col-sm-6">
<usermgr-permission-list group="group"></usermgr-permission-list>
<button type="button" class="btn btn-md btn-primary" ng-click="btnSave_click($event)">SAVE</button>
</div>
<div class="col-sm-6">
<usermgr-user-list group="group"></usermgr-user-list>
</div>
</div>
</div>
</div>
My controller is :
(function (module) {
'use strict';
module.controller('groupCreateController', function ($scope, $rootScope, $routeParams, $location, userGroupService, $mdDialog) {
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group[0].id = info.id;
$scope.group[0].name = info.name;
$scope.group[0].description = info.description;
console.log($scope.group);
// $rootScope.$broadcast('rCube-user-mgt-users-list', info.id);
// $rootScope.$broadcast('rCube-user-mgt-permissions-list', info.id);
}
else {
}
}).catch(function (exception) {
console.error(exception);
});
}
$scope.init();
});
})(angular.module('r-cube-user-mgt.user-group'));
I have two custom directives in the first block of code for user permissions and users. The group scope that i pass with the directive does not contain the values i put in the getUserGroup(id) function. The group name and group description shows up so the scope.group in the controller is filled, however thats not the case once i pass it to my directives. here is the directives code as well :
permissions list :
(function (module) {
'use strict';
module.directive('usermgrPermissionList', function () {
return {
restrict: 'E',
scope:{
group: '='
},
controller: function ($scope, permissionService) {
$scope.updatedPermissions=[];
console.log($scope.group); //it doesnt have the values from the controller ..
if (!$scope.group.hasOwnProperty('permissions')) {
$scope.group.permissions = [];
}
function getData() {
console.log("inside getDAta for permission list" + $scope.group.id;
permissionService.getPermissionsFiltered($scope.group.id).then(function (info) {
if (info && info.length > 0) {
console.log(info);
$scope.group.permissions = info.map(function (a, index, array) {
return {
id: a.id,
name: a.name,
description: a.description,
assigned: a.assigned
};
});
}
}).catch(function (exception) {
console.error(exception);
});
} //end of getData()
$scope.init = function () {
getData();
};
$scope.init();
},
templateUrl: 'r-cube-user-mgt/permission/list/list.tpl.html'
};
});
})(angular.module('r-cube-user-mgt.permission'));
can anyone help?
you cannot assign property to an array like this $scope.group.id = 0;
either make $scope.group object
$scope.group = {};
or add properties to an index
$scope.group = [];
$scope.init = function () {
if ($routeParams.hasOwnProperty('id')) {
//edit mode
// $scope.trans.heading = 'Edit Release';
// $scope.trans.saveBtn = 'Save';
var id = parseInt($routeParams.id);
getUserGroup(id);
} else {
$scope.group[0].id = 0;
$scope.group[0].permissions = [];
$scope.assignedPermissions = [];
$scope.enrolledUsers = [];
$scope.group[0].users = [];
$scope.group[0].name = '';
$scope.group[0].description = '';
}
};
So I solved the issue by adding broadcast to send the id when the directive loads. This worked!
in the Group controller i add broadcast and send the group.id
function getUserGroup(id) {
userGroupService.getbyid(id).then(function (info) {
if (info !== undefined && info.id === id) {
$scope.group.id = info.id;
$scope.group.name = info.name;
$scope.group.description = info.description;
console.log($scope.group);
$rootScope.$broadcast(rCubeTopics.userMgtPermissionLoadData, $scope.group.id);
}
}).catch(function (exception) {
console.error(exception);
});
}
and in the permission directive get that broadcast :
$scope.$on(rCubeTopics.userMgtPermissionLoadData, function (event, id) {
console.log($scope.group.id);
getData();
});

How to check whether an object is empty in a span?

I have some objects in my angularjs controller.
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.notes = [];
$scope.note = {};
$scope.submit = function() {
$scope.notes.push($scope.note);
$scope.note = {};
};
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
});
I need to check whether the draft object is empty, and output the save successfully information.
<span data-ng-hide="draft == {}" style="color:green">Your note has been saved.</span>
I have also tried:
<span data-ng-hide="draft.length == -1" style="color:green">Your note has been saved.</span>
or
<span data-ng-hide="draft == ''" style="color:green">Your note has been saved.</span>
But all of them are failed.
Add function isEmptyObject in your controller:
var app = angular.module("myApp", []);
app.controller("noteCtrl", function ($scope) {
$scope.draft = {};
$scope.note = {};
$scope.notes = [];
$scope.save = function() {
if ($scope.button == "Save") {
$scope.draft = angular.copy($scope.note);
} else {
$scope.note = $scope.draft;
}
};
$scope.cancel = function() {
$scope.note = {};
}
$scope.isEmptyObject = function (obj) {
for (var i in obj) if (obj.hasOwnProperty(i)) return false;
return true;
};
});
Or you can use this function:
$scope.isEmptyObject = function (obj) {
return Object.keys(obj).length === 0;
}
HTML:
<span data-ng-hide="isEmptyObject(draft)" style="color:green">Your note has been saved.</span>
Please initialize null instead of empty object
$scope.draft = null;
And html should be
<span data-ng-hide="!draft" style="color:green">Your note has been saved.</span>
You can chek the condition inline in your span.
HTML:
<span data-ng-hide="Object.keys(draft).length === 0" style="color:green">Your note has been saved.</span>

How to get selected value from ng-autocomplete directive to controller

I am using a directive for auto complete / auto suggest in angular Js taken from http://demo.jankuri.com/ngAutocomplete/. It is working fine getting the data from server and filtering it. But I am facing problem into select and use that select item from the auto complete.
Here is the code of directive what I am using for this...
app.factory('ngAutocompleteService', ['$http', function($http)
{
var self = this;
self.getData = function (url, keyword) {
return $http.get(url, { query: keyword });
};
return self;
}])
app.directive('ngAutocomplete', ['$timeout','$filter','ngAutocompleteService',
function($timeout, $filter, ngAutocompleteService)
{
'use strict';
var keys = {
left : 37,
up : 38,
right : 39,
down : 40,
enter : 13,
esc : 27
};
var setScopeValues = function (scope, attrs) {
scope.url = base_url+attrs.url || null;
scope.searchProperty = attrs.searchProperty || 'skills';
scope.maxResults = attrs.maxResults || 10;
scope.delay = parseInt(attrs.delay, 10) || 300;
scope.minLenth = parseInt(attrs.minLenth, 10) || 2;
scope.allowOnlyResults = scope.$eval(attrs.allowOnlyResults) || false;
scope.placeholder = attrs.placeholder || 'Search...';
};
var delay = (function() {
var timer = 0;
return function (callback, ms) {
$timeout.cancel(timer);
timer = $timeout(callback, ms);
};
})();
return {
restrict: 'E',
require: '?ngModel',
scope: true,
link: function(scope, element, attrs, ngModel) {
setScopeValues(scope, attrs);
scope.results = [];
scope.currentIndex = null;
scope.getResults = function () {
if (parseInt(scope.keyword.length, 10) === 0) scope.results = [];
if (scope.keyword.length < scope.minLenth) return;
delay(function() {
ngAutocompleteService.getData(scope.url, scope.keyword).then(function(resp) {
scope.results = [];
var filtered = $filter('filter')(resp.data, {skills: scope.keyword});
for (var i = 0; i < scope.maxResults; i++) {
scope.results.push(filtered[i]);
}
scope.currentIndex = 0;
if (scope.results.length) {
scope.showResults = true;
}
});
}, scope.delay);
};
scope.selectResult = function (r) {
scope.keyword = r.skills;
ngModel.$setViewValue(r.skills);
scope.ngModel = r.skills;
ngModel.$render();
scope.showResults = false;
};
scope.clearResults = function () {
scope.results = [];
scope.currentIndex = null;
};
scope.hoverResult = function (i) {
scope.currentIndex = i;
}
scope.blurHandler = function () {
$timeout(function() {
if (scope.allowOnlyResults) {
var find = $filter('filter')(scope.results, {skills: scope.keyword}, true);
if (!find.length) {
scope.keyword = '';
ngModel.$setViewValue('');
}
}
scope.showResults = false;
}, 100);
};
scope.keyupHandler = function (e) {
var key = e.which || e.keyCode;
if (key === keys.enter) {
scope.selectResult(scope.results[scope.currentIndex]);
}
if (key === keys.left || key === keys.up) {
if (scope.currentIndex > 0) {
scope.currentIndex -= 1;
}
}
if (key === keys.right || key === keys.down) {
if (scope.currentIndex < scope.maxResults - 1) {
scope.currentIndex += 1;
}
}
if (key === keys.esc) {
scope.keyword = '';
ngModel.$setViewValue('');
scope.clearResults();
}
};
},
template:
'<input type="text" class="form-control" ng-model="keyword" placeholder="{{placeholder}}" ng-change="getResults()" ng-keyup="keyupHandler($event)" ng-blur="blurHandler()" ng-focus="currentIndex = 0" autocorrect="off" autocomplete="off">' +
'<input type="hidden" ng-model="skillIdToBeRated">'+
'<div ng-show="showResults">' +
' <div ng-repeat="r in results | filter : {skills: keyword}" ng-click="selectResult(r)" ng-mouseover="hoverResult($index)" ng-class="{\'hover\': $index === currentIndex}">' +
' <span class="form-control">{{ r.skills }}</span>' +
' </div>' +
'</div>'
};
}]);
I am unable to get value which is selected by ng-click="selectResult(r)" function. The value is showing into text field but not getting it into controller.
I was also using the same directive for showing the auto complete text box. I have tried the following for getting the selected value from auto complete.
in HTML
<div ng-controller="Cntrl as cntrl">
<ng-autocomplete ng-model="cntrl.selectedValue" url="url" search-property="keyword" max-results="10" delay="300" min-length="2" allow-only-results="true"></ng-autocomplete>
</div>
in JavaScript
app.controller('Cntrl', function($scope, $http) {
var self = this;
self.selectedValue = '';
$scope.getSelectedValue = function(){
console.log(self.selectedValue);
}
});
I hope this may help you.
I ran into the same issue. I ended up just watching the property from the details attribute in the ng-autocomplete input and it works pretty well.
$scope.$watch(function() {
return vm.location_result;
}, function(location) {
if (location) {
vm.location_list.push(location);
vm.location = '';
}
});
Fiddle Example: http://jsfiddle.net/n3ztwucL/
GitHub Gist: https://gist.github.com/robrothedev/46e1b2a2470b1f8687ad

Angularjs expression is not working

I tried to use the angular expression below in html 5 but it is not working.
index.html
* * < !DOCTYPE html >
< html >
< script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js" > < /script> < script src = "blockuijs.js" > < /script> < body >
< div ng - app = "icebreakerapp" >
< p > My first expression: {
{
5 + 5
}
} </p> </div> < script >
var module = angular.module('icebreakerapp', ['blockUI']); < /script> < /body> < /html>**
blockuijs.js
(function(angular) {
var blkUI = angular.module('blockUI', []);
blkUI.config(["$provide", "$httpProvider", function($provide, $httpProvider) {
$provide.decorator('$exceptionHandler', ['$delegate', '$injector', function($delegate, $injector) {
var blockUI, blockUIConfig;
return function(exception, cause) {
blockUIConfig = blockUIConfig || $injector.get('blockUIConfig');
if (blockUIConfig.resetOnException) {
blockUI = blockUI || $injector.get('blockUI');
blockUI.instances.reset();
}
$delegate(exception, cause);
};
}]);
$httpProvider.interceptors.push('blockUIHttpInterceptor');
}]);
blkUI.run(["$document", "blockUIConfig", "$templateCache", function($document, blockUIConfig, $templateCache) {
if (blockUIConfig.autoInjectBodyBlock) {
$document.find('body').attr('block-ui', 'main');
}
if (blockUIConfig.template) {
blockUIConfig.templateUrl = '$$block-ui-template$$';
$templateCache.put(blockUIConfig.templateUrl, blockUIConfig.template);
}
}]);
blkUI.directive('blockUiContainer', ["blockUIConfig", "blockUiContainerLinkFn", function(blockUIConfig, blockUiContainerLinkFn) {
return {
scope: true,
restrict: 'A',
templateUrl: blockUIConfig.templateUrl,
compile: function($element) {
return blockUiContainerLinkFn;
}
};
}]).factory('blockUiContainerLinkFn', ["blockUI", "blockUIUtils", function(blockUI, blockUIUtils) {
return function($scope, $element, $attrs) {
var srvInstance = $element.inheritedData('block-ui');
if (!srvInstance) {
throw new Error('No parent block-ui service instance located.');
}
$scope.state = srvInstance.state(); //
};
}]);
blkUI.directive('blockUi', ["blockUiCompileFn", function(blockUiCompileFn) {
return {
scope: true,
restrict: 'A',
compile: blockUiCompileFn
};
}]).factory('blockUiCompileFn', ["blockUiPreLinkFn", function(blockUiPreLinkFn) {
return function($element, $attrs) {
$element.append('<div block-ui-container class="block-ui-container"></div>');
return {
pre: blockUiPreLinkFn
};
};
}]).factory('blockUiPreLinkFn', ["blockUI", "blockUIUtils", "blockUIConfig", function(blockUI, blockUIUtils, blockUIConfig) {
return function($scope, $element, $attrs) {
if (!$element.hasClass('block-ui')) {
$element.addClass(blockUIConfig.cssClass);
}
$attrs.$observe('blockUiMessageClass', function(value) {
$scope.$_blockUiMessageClass = value;
});
var instanceId = $attrs.blockUi || '_' + $scope.$id;
var srvInstance = blockUI.instances.get(instanceId);
if (instanceId === 'main') {
var fn = $scope.$on('$viewContentLoaded', function($event) {
fn();
$scope.$on('$locationChangeStart', function(event) {
if (srvInstance.state().blockCount > 0) {
event.preventDefault();
}
});
});
} else {
var parentInstance = $element.inheritedData('block-ui');
if (parentInstance) {
srvInstance._parent = parentInstance;
}
}
$scope.$on('$destroy', function() {
srvInstance.release();
});
srvInstance.addRef();
$scope.$_blockUiState = srvInstance.state();
$scope.$watch('$_blockUiState.blocking', function(value) {
$element.attr('aria-busy', !!value);
$element.toggleClass('block-ui-visible', !!value);
});
$scope.$watch('$_blockUiState.blockCount > 0', function(value) {
$element.toggleClass('block-ui-active', !!value);
});
var pattern = $attrs.blockUiPattern;
if (pattern) {
var regExp = blockUIUtils.buildRegExp(pattern);
srvInstance.pattern(regExp);
}
$element.data('block-ui', srvInstance);
};
}]);
blkUI.constant('blockUIConfig', {
templateUrl: 'angular-block-ui/angular-block-ui.ng.html',
delay: 250,
message: "Loading ...",
autoBlock: true,
resetOnException: true,
requestFilter: angular.noop,
autoInjectBodyBlock: true,
cssClass: 'block-ui block-ui-anim-fade'
});
blkUI.factory('blockUIHttpInterceptor', ["$q", "$injector", "blockUIConfig", function($q, $injector, blockUIConfig) {
var blockUI;
function injectBlockUI() {
blockUI = blockUI || $injector.get('blockUI');
}
function stopBlockUI(config) {
if (blockUIConfig.autoBlock && !config.$_noBlock && config.$_blocks) {
injectBlockUI();
config.$_blocks.stop();
}
}
function error(rejection) {
stopBlockUI(rejection.config);
return $q.reject(rejection);
}
return {
request: function(config) {
if (blockUIConfig.autoBlock) {
if (blockUIConfig.requestFilter(config) === false) {
config.$_noBlock = true;
} else {
injectBlockUI();
config.$_blocks = blockUI.instances.locate(config);
config.$_blocks.start();
}
}
return config;
},
requestError: error,
response: function(response) {
stopBlockUI(response.config);
return response;
},
responseError: error
};
}]);
blkUI.factory('blockUI', ["blockUIConfig", "$timeout", "blockUIUtils", "$document", function(blockUIConfig, $timeout, blockUIUtils, $document) {
var $body = $document.find('body');
function BlockUI(id) {
var self = this;
var state = {
id: id,
blockCount: 0,
message: blockUIConfig.message,
blocking: false
},
startPromise, doneCallbacks = [];
this._refs = 0;
this.start = function(message) {
if (state.blockCount > 0) {
message = message || state.message || blockUIConfig.message;
} else {
message = message || blockUIConfig.message;
}
state.message = message;
state.blockCount++;
var $ae = angular.element($document[0].activeElement);
if ($ae.length && blockUIUtils.isElementInBlockScope($ae, self)) { //
self._restoreFocus = $ae[0];
$timeout(function() {
if (self._restoreFocus) {
self._restoreFocus.blur();
}
});
}
if (!startPromise) {
startPromise = $timeout(function() {
startPromise = null;
state.blocking = true;
}, blockUIConfig.delay);
}
};
this._cancelStartTimeout = function() {
if (startPromise) {
$timeout.cancel(startPromise);
startPromise = null;
}
};
this.stop = function() {
state.blockCount = Math.max(0, --state.blockCount);
if (state.blockCount === 0) {
self.reset(true);
}
};
this.message = function(value) {
state.message = value;
};
this.pattern = function(regexp) {
if (regexp !== undefined) {
self._pattern = regexp;
}
return self._pattern;
};
this.reset = function(executeCallbacks) {
self._cancelStartTimeout();
state.blockCount = 0;
state.blocking = false;
if (self._restoreFocus && (!$document[0].activeElement || $document[0].activeElement === $body[0])) {
self._restoreFocus.focus();
self._restoreFocus = null;
}
try {
if (executeCallbacks) {
angular.forEach(doneCallbacks, function(cb) {
cb();
});
}
} finally {
doneCallbacks.length = 0;
}
};
this.done = function(fn) {
doneCallbacks.push(fn);
};
this.state = function() {
return state;
};
this.addRef = function() {
self._refs += 1;
};
this.release = function() {
if (--self._refs <= 0) {
mainBlock.instances._destroy(self);
}
};
}
var instances = [];
instances.get = function(id) {
var instance = instances[id];
if (!instance) {
instance = instances[id] = new BlockUI(id);
instances.push(instance);
}
return instance;
};
instances._destroy = function(idOrInstance) {
if (angular.isString(idOrInstance)) {
idOrInstance = instances[idOrInstance];
}
if (idOrInstance) {
idOrInstance.reset();
delete instances[idOrInstance.state().id];
var i = instances.length;
while (--i) {
if (instances[i] === idOrInstance) {
instances.splice(i, 1);
break;
}
}
}
};
instances.locate = function(request) {
var result = [];
blockUIUtils.forEachFnHook(result, 'start');
blockUIUtils.forEachFnHook(result, 'stop');
var i = instances.length;
while (i--) {
var instance = instances[i];
var pattern = instance._pattern;
if (pattern && pattern.test(request.url)) {
result.push(instance);
}
}
if (result.length === 0) {
result.push(mainBlock);
}
return result;
};
blockUIUtils.forEachFnHook(instances, 'reset');
var mainBlock = instances.get('main');
mainBlock.addRef();
mainBlock.instances = instances;
return mainBlock;
}]);
blkUI.factory('blockUIUtils', function() {
var $ = angular.element;
var utils = {
buildRegExp: function(pattern) {
var match = pattern.match(/^\/(.*)\/([gim]*)$/),
regExp;
if (match) {
regExp = new RegExp(match[1], match[2]);
} else {
throw Error('Incorrect regular expression format: ' + pattern);
}
return regExp;
},
forEachFn: function(arr, fnName, args) {
var i = arr.length;
while (i--) {
var t = arr[i];
t[fnName].apply(t, args);
}
},
forEachFnHook: function(arr, fnName) {
arr[fnName] = function() {
utils.forEachFn(this, fnName, arguments);
}
},
isElementInBlockScope: function($element, blockScope) {
var c = $element.inheritedData('block-ui');
while (c) {
if (c === blockScope) {
return true;
}
c = c._parent;
}
return false;
},
findElement: function($element, predicateFn, traverse) {
var ret = null;
if (predicateFn($element)) {
ret = $element;
} else {
var $elements;
if (traverse) {
$elements = $element.parent();
} else {
$elements = $element.children();
}
var i = $elements.length;
while (!ret && i--) {
ret = utils.findElement($($elements[i]), predicateFn, traverse);
}
}
return ret;
}
};
return utils;
});
angular.module('blockUI').run(['$templateCache', function($templateCache) {
$templateCache.put('angular-block-ui/angular-block-ui.ng.html', '<div class=\"block-ui-overlay\"></div><div class=\"block-ui-message-container\" aria-live=\"assertive\" aria-atomic=\"true\"><div class=\"block-ui-message loading_spinnerlatest\" ng-class=\"$_blockUiMessageClass\">{{ state.message }}</div></div>');
}]);
})(angular); //
It is giving the output as "My first expression:{{ 5+5}}".But expectation is "My first expression:10"
Note: If I remove dependency modules in (angular.module) it is working.But I need those dependency modules
for further development
Are you seeing any error in console? Maybe some of your module dependencies are not resolved.
Check this snippet:
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="icebreakerapp">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
<script>
var module = angular.module('icebreakerapp', []);
</script>

Resources