error when injecting $modal in angular - html

I am trying to open a modal popup based on some condition. However i am getting the below error
Error: [$injector:unpr] http://errors.angularjs.org/1.2.3/$injector/unpr?p0=%24modalProvider%20%3C-%20%24modal
at Error (<anonymous>)
Below is my Code: "ui.bootstrap" is included in the app.
angular.module('myApp').controller('myController', function ($scope, $timeout, $location, $window, $log, $rootScope, $modal) {
$scope.selectRow = function (position) {
$scope.changed = false;
if ($scope.select !== undefined && $scope.selectedRow !== position){
$scope.changed = true;
$scope.open();
}
$scope.select = position;
};
$scope.open = function () {
console.log('Opening modal');
var modalInstance = {
templateUrl: 'modal.html',
dialogClass: 'modal-selection',
controller: ModalInstanceCtrl
};
$modal.open(modalInstance);
};
var ModalInstanceCtrl = function ($modalInstance) {
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
});
My HTML:
<div id="modal-select" >
<h3>
Choose appropriate change
</h3>
<div>
<ul>
<li>Change 1</li>
<li>Change 2</li>
<li>Change 3</li>
<li>Change 4</li>
</ul>
</div>
<div>
<button class="button" ng-click="cancel()">
Cancel
</button>
<button class="button" ng-click="ok()">
Done
</button>
</div>
</div>

From the Angular website:
This error results from the $injector being unable to resolve a required dependency. To fix this, make sure the dependency is defined and spelled correctly. For example
Do you have 'ui.bootstrap' as a dependency to your current module?
angular.module('myApp').controller('myController', function ($scope, $timeout, $location, $window, $log, $rootScope, $modal)
Should be:
angular.module('myApp', ['ui.bootstrap']).controller('myController', function ($scope, $timeout, $location, $window, $log, $rootScope, $modal)

The error was because i had ui.bootstrap 0.5.0. I updated to 0.6.0 and rebuild the application to include this and the issue was fixed.

I solve this problem, by simply append the $modal.open({... to $scope.modalInstance variable.
(function () {
var app = angular.module('app');
app.controller('ModalCtrl', [
'$scope', '$modal', function ($scope, $modal) {
$scope.modalInstance = {};
$scope.open = function () {
$scope.modalInstance = $modal.open({
templateUrl: 'Template id goes here',
controller: 'ModalInstanceCtrl'
});
};
}
]); })();
The 'ModalInstanceCtrl'
(function () {
var app = angular.module('app');
app.controller('ModalInstanceCtrl', function ($scope, $modalInstance) {
$scope.submit = function (myForm) {
//submit code goes here
};
$scope.cancel = function () {
$modalInstance.close();
};
}
); })();

Related

Closing bootstrap uibmodal from a different file

I am opening a uibModal each time a page is opened like:
genres.js
app.controller('genresController', ['$scope', '$http', '$uibModal', 'blockUI', 'notifyService', 'lib',
function ($scope, $http, $uibModal,blockUI, notifyService, lib) {
$scope.genres = [];
var init = function () {
//Initial code
loadGenres();
};
var loadGenres = function () {
/*... some non-important codes... */
openFavoriteGenreDialog();
/*... some non-important codes... */
}, lib.handleError);
};
var openFavoriteGenreDialog = function () {
var modalInstance = $uibModal.open({
templateUrl: '/Dialog/FavoriteGenre',
controller: 'favoriteGenreDialogController'
});
modalInstance.result.then(function (msg) {
}, function (msg) {
//dismiss callback
});
};
init();
}]);
and the modal controller is in another file and the html of that modal has a cancel button.
FavoriteGenre.cshtml
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
That cancel button is beeing treated in another controller that has the function that so far looks like it
favGenrer.js
$scope.cancel = function () {
var modalInstance = $uibModal.open({
templateUrl: '/Dialog/FavoriteGenre',
controller: 'favoriteGenreDialogController'
});
modalInstance.close();
};
Because of that construction, I'm opening and closing the modal each time I press the cancel button. There is anyway so I can close the modal when I press the close button even if the cancel() funcion is in another controller that is in another file? I tried to put the cancel() function on genres.js but I wasn't able to make the html call the genresController without getting lot of erros because of the genresControllers other methods.
ANSWER
find out! the problem was that in the FavoriteGenre.cshtml I was doing
<div ng-controller="favoriteGenreDialogController" block-ui="genresContentDiv">
I just needed to let it be like:
<div block-ui="genresContentDiv">
and it worked using the
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
Try this.
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};

mocking bootstrap datepicker in jasmine

I am trying to access datepicker onClose method via mocking its not working.i have injected all required bootstrap module in spec file
define(['angular', 'app'], function(angular, myApp) {
myApp.directive('customdate', function() {
var linkFn = function(scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: attrs.format || 'yy/mm/dd',
changeMonth: true,
changeYear: true,
onClose: function(date) {
if (attrs.datetype === 'fromField') {
var elem = angular.element('#' + attrs.todateid);
elem.datepicker("option", "minDate", date).datepicker('setDate', date).focus();
var toDate = date || '';
scope.dateRange[attrs.todateid] = toDate;
setTimeout(function() {
elem.datepicker('show')
}, 0);
}
}
});
};
return {
restrict: 'A',
require: 'ngModel',
link: linkFn
};
});});
and in spec file i m trying to validate directive which is using datepicker in link function
define(
['jquery', 'angular', 'app', 'uiBootstrap',
'datepicker_drtv'
],
function() {
'use strict';
describe('Test Suit', function() {
var datePickerElement;
var $compile, $rootScope, scope;
var tpl;
beforeEach(function() {
angular.mock.module('myApp');
angular.mock.inject(function(_$rootScope_, _$compile_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
});
});
it('- check initial setup', function() {
scope.startDate = '2016-09-29T00:00:00.000+0000';
tpl = "<input type='text' id='startdateFrom' customdate datetype='fromField' todateid='startdateTo' class='fromTxt' ng-model='startDate' readonly />";
var element = $compile(tpl)(scope);
scope.$digest();
element.val(scope.startDate).trigger("input");
element.datepicker('option', 'onClose');
var eVal = element.val();
expect(angular.element(element).val()).toEqual(eVal);
});
});
});
test case is not failing but in coverage report, link function is not covering

Hello how to upload an image using angularjs+mysql+node.js

How to upload the image in angularjs and mysql and node.js?
<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
AngularJs is a client side language. so it is not able to direct save data to MySql.
If any data is store in a database or in a server you must used any server side language.
You are create a web service that can tack response from client side (AngularJS) and send proper response.
File Upload in Mysql using NodeJs
fs.open(temp_path, 'r', function (status, fd) {
if (status) {
console.log(status.message);
return;
}
var buffer = new Buffer(getFilesizeInBytes(temp_path));
fs.read(fd, buffer, 0, 100, 0, function (err, num) {
var query = "INSERT INTO `files` SET ?",
values = {
file_type: 'img',
file_size: buffer.length,
file: buffer
};
mySQLconnection.query(query, values, function (er, da) {
if (er)throw er;
});
});
});
function getFilesizeInBytes(filename) {
var stats = fs.statSync(filename)
var fileSizeInBytes = stats["size"]
return fileSizeInBytes
}

Cannot read property 'toLowerCase' of undefined angularjs

I'm trying to make a search function in my angularjs "webapp". When I search in products all works fine, but when I change everything so that it searches into users, i get an error Cannot read property 'toLowerCase' of undefined.
Here's my js:
return function(arr, searchString){
if(!searchString){
return arr;
}
var result = [];
searchString = searchString.toLowerCase();
angular.forEach(arr, function(item){
if(item.title.toLowerCase().indexOf(searchString) !== -1){
result.push(item);
}
});
return result;
};
});
And here's the html that's calling it:
<div ng-controller="userCtrl" class="container-app">
<div class="bar">
<input type="text" class="search" ng-model="searchString" placeholder="Enter your search terms" />
</div>
<div class="searchResultsText">
<h2>Zoekresultaten: </h2>
</div>
<div class="searchResults" ng-repeat="user in users | searchFor:searchString">
<a class="normal" href="#">{{user.name}}</a>
</div>
it does show me the list of users, just as soon as I start typing in the search bar it gives me the error.
when I use the exact same function, with a different controller it works. Here are the 2 controllers:
app.controller('customersCtrl', function ($scope, $http) {
$http.get(apiUrl + "product/list")
.success(function (response) {
$scope.products = response;
});
});
app.controller('userCtrl', function ($scope, $http) {
$http.get(apiUrl + "user/list")
.success(function (response) {
$scope.users = response;
});
});
so basically customerCtrl works fine, but when i change values to userCtrl it stops working.
any suggestions?
Most likely item.title is at least once undefined.
return function(arr, searchString){
if(!searchString){
return arr;
}
var result = [];
searchString = searchString.toLowerCase();
angular.forEach(arr, function(item){
if(
angular.isDefined(item.title) &&
item.title.toLowerCase().indexOf(searchString) !== -1
){
result.push(item);
}
});
return result;
};

I want to use ng-contextmenu on my html page for providing different menu items. But my JS class is not getting called.

This is my html class, I have used one example from net for understanding how it's works.
<form>
<div ng-controller="ListController">
<div>
<strong>Gold: </strong>
{{player.gold}}
</div>
<div class="list-group">
<a href="#"
class="list-group-item"
ng-repeat="item in items"
context-menu="menuOptions">
<span class="badge">{{item.cost}}</span>
{{item.name}}
</a>
</div>
</div>
</form>
This is controller :
controller('ListController', ['$scope',
function ($scope) {
$scope.player = {
gold: 100
};
$scope.items = [
{ name: 'Small Health Potion', cost: 4 },
{ name: 'Small Mana Potion', cost: 5 },
{ name: 'Iron Short Sword', cost: 12 }
];
$scope.menuOptions = [
['Buy', function ($itemScope) {
$scope.player.gold -= $itemScope.item.cost;
}],
null,
['Sell', function ($itemScope) {
$scope.player.gold += $itemScope.item.cost;
}]
];
}
]);
This is my JS file, which is being used for contextmenu:
var app = angular.module("contextMenu",[]);
app.directive('contextMenu', function ($parse) {
var renderContextMenu = function ($scope, event, options) {
if (!$) { var $ = angular.element; }
$(event.currentTarget).addClass('context');
var $contextMenu = $('<div>');
$contextMenu.addClass('dropdown clearfix');
var $ul = $('<ul>');
$ul.addClass('dropdown-menu');
$ul.attr({ 'role': 'menu' });
$ul.css({
display: 'block',
position: 'absolute',
left: event.pageX + 'px',
top: event.pageY + 'px'
});
angular.forEach(options, function (item, i) {
var $li = $('<li>');
if (item === null) {
$li.addClass('divider');
} else {
$a = $('<a>');
$a.attr({ tabindex: '-1', href: '#' });
$a.text(typeof item[0] == 'string' ? item[0] : item[0].call($scope, $scope));
$li.append($a);
$li.on('click', function ($event) {
$event.preventDefault();
$scope.$apply(function () {
$(event.currentTarget).removeClass('context');
$contextMenu.remove();
item[1].call($scope, $scope);
});
});
}
$ul.append($li);
});
$contextMenu.append($ul);
var height = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
$contextMenu.css({
width: '100%',
height: height + 'px',
position: 'absolute',
top: 0,
left: 0,
zIndex: 9999
});
$(document).find('body').append($contextMenu);
$contextMenu.on("mousedown", function (e) {
if ($(e.target).hasClass('dropdown')) {
$(event.currentTarget).removeClass('context');
$contextMenu.remove();
}
}).on('contextmenu', function (event) {
$(event.currentTarget).removeClass('context');
event.preventDefault();
$contextMenu.remove();
});
};
return function ($scope, element, attrs) {
element.on('contextmenu', function (event) {
$scope.$apply(function () {
event.preventDefault();
var options = $scope.$eval(attrs.contextMenu);
if (options instanceof Array) {
renderContextMenu($scope, event, options);
} else {
throw '"' + attrs.contextMenu + '" not an array';
}
});
});
};
});
But this code is not working for me. My debug point never comes on contextmenu js file. And I am getting default window menu on right click.
Can anyone please suggest what I am doing wrong or missing in this. It would be a great help.
First you have to create a master app.js file to define your modules something like below. The file needs to be loaded first.
(function () {
var module = angular.module('app', [
'contextMenu',
'menu'
]);
})();
Now the file which holds controller needs to be something like below.
(function () {
var module = angular.module('menu');
module.controller('ListController', [
'$scope'
function ($scope) {
//Your controller code goes here
}]);
})();
Your html needs to be something like below.
<body ng-app="app">
//Your html goes here
</body>
Your js files needs to be added in below order.
Angularjs
app.js
menu.js
That's all i can say for now.