I have the following directive riding a modal. File: login.component.js
(function() {
'use strict';
var app = angular.module('myapp');
app.directive('loginComponent', ['loginService', function(loginService){
return {
templateUrl: 'app/components/login/login.html',
restrict: 'E',
replace: true,
controller: 'homeCrotroller',
link: function ($scope) {
$scope.submit = function() {
$scope.login();
$("#modal-login").modal('hide');
};
$scope.cancel = function() {
$scope.loggingIn = false;
$("#modal-login").modal('hide');
};
$scope.$watch('loggingIn', function() {
if ($scope.loggingIn) {
$("#modal-login").modal('show');
};
});
}
};
}]);
})();
And the next controller. File: home.controller.js
(function() {
'use strict';
var app = angular.module('myapp');
app.controller('homeCrotroller', ['$scope', function($scope){
$scope.loggedIn = false;
$scope.loggingIn = false;
$scope.showLogin = function () {
$scope.loggingIn = true;
};
$scope.logout = function () {
$scope.user = null;
$scope.loggedIn = false;
};
$scope.login = function () {
$scope.loggingIn = false;
$scope.loggedIn = true;
};
}]);
})();
And in my view I call showLogin()
<a class="login" id="btn-login" href="javascript:void(0);" ng-click="showLogin()" title="Entrar">Entrar</a>
This function changes the value of $scope.logging In to true, only this value is not reaching policy. Only reaches the first status (loading screen) that is false
Related
I am uplifting a chat application from AngularJS to VueJS and I don't have much clue about how the AngularJS. There isn't really a great resources available on AngularJS right now to gain some insight.
If someone could help me in this I'd really appreciate it.
I wish to convert this below AngularJS code to VueJS completely.
var app = angular.module('IBMfinder', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider, settings) {
$routeProvider
.when('/main', {
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
.when('/find', {
templateUrl: 'find.html',
controller: 'findCtrl',
})
.when('/chat', {
templateUrl: 'chat.html',
controller: 'chatCtrl',
})
.otherwise({
templateUrl: 'welcome.html',
controller: 'welcomeCtrl',
})
}])
app.controller('userCount', ['$scope', 'socket', function($scope,
socket){
socket.on('userCount', function(amount){
$scope.online = amount;
})
}]);
app.controller('welcomeCtrl', ['$scope', '$location', 'settings',
'socket', function($scope, $location, settings, socket){
$scope.users = 13;
if(settings.getUsername()!==""){
socket.emit('delete');
settings.reset();
}
$scope.enter = function(){
settings.setUsername($scope.name);
$location.path('/find');
}
}]);
app.controller('findCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', function($scope, $location, settings,
socket, $rootScope){
$scope.username = settings.getUsername();
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
if(settings.exists){
socket.emit('delete');
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('match', function (data) {
settings.setPartner(data['username'], data['id']);
$location.path('/chat');
});
}]);
app.controller('chatCtrl', ['$scope', '$location', 'settings',
'socket', '$rootScope', '$timeout', '$window', '$interval',
function($scope, $location, settings, socket, $rootScope, $timeout,
$window, $interval){
var typing = false;
var focus = true;
var titleTimer;
var onFocus = function(){
focus = true;
$interval.cancel(titleTimer);
document.title = 'Chat-Box';
}
var onBlur = function(){
focus = false;
}
$window.onfocus = onFocus;
$window.onblur = onBlur;
$scope.username = settings.getUsername();
$scope.partnerTyping = false;
if(!$scope.username || $scope.username == ""){
location.href = "index.html";
}
$scope.chatlog = [];
if(!settings.exists){
var username = $scope.username;
settings.setExists(true);
socket.emit('new user', username );
};
socket.on('incoming message', function(data){
if($scope.chatlog[$scope.chatlog.length-1]){
if($scope.chatlog[$scope.chatlog.length-1].sentby == data.userID){
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: '',
chatmessage: data.message
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
}else{
$scope.chatlog[ $scope.chatlog.length] = {
sentby:data.userID,
chatusername: data.user + ": ",
chatmessage: data.message
}
}
if(!focus){
document.title = 'New Message!';
$interval.cancel(titleTimer);
titleTimer = $interval(function(){
if(document.title == 'New Message!'){
document.title = 'Chat-Box';
}else{
document.title = 'New Message!';
}
}, 1000)
}
});
socket.on('aborted', function(data){
alert('Your partner left, sorry!');
socket.emit('delete');
settings.reset();
location.href = "index.html";
})
$scope.typing = function(){
if(!typing){
socket.emit('typing', settings.getID());
typing = true;
var stop = $timeout(function() {
typing = false;
socket.emit('stop typing', settings.getID());
}, 2000);
}
}
socket.on('typing', function(data){
$scope.partnerTyping = true;
$('#chatbox').scrollTop(10000);
})
socket.on('stop typing', function(data){
$scope.partnerTyping = false;
$('#chatbox').scrollTop(10000);
})
$scope.sendMessage = function(){
if($scope.message==""){
}else{
socket.emit( 'new message', {
message:$scope.message,
partner:$scope.partner,
partnerID: settings.getID()
});
}
$scope.message = "";
}
$scope.partner = settings.getPartner();
}]);
app.service('settings', function() {
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
this.setExists = function(bool){
this.exists = bool;
}
this.setUsername = function(uname){
this.username = uname;
}
this.getUsername = function(){
return(this.username);
}
this.setUserID = function(id){
this.userdata.id = id;
}
this.getuserdata = function(){
return(this.userdata);
}
this.setPartner = function(uname, id){
this.partner = uname;
this.partnerID = id;
}
this.getPartner = function(){
return(this.partner);
}
this.getID = function(){
return(this.partnerID);
}
this.reset = function(){
this.exists = false;
this.username = "";
this.partner = "";
this.partnerID = "";
this.userdata = {}
}
});
app.factory('socket', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
},
disconnect: function(id){
socket.disconnect(id);
}
};
});
app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
});
app.directive('schrollBottom', function () {
return {
scope: {
schrollBottom: "="
},
link: function (scope, element) {
scope.$watchCollection('schrollBottom', function (newValue) {
if (newValue)
{
$(element).scrollTop(100000);
}
});
}
}
})
It'd be great if someone could point me to any great resources. I've not had any luck since past week regarding this.
Video Tutorials
https://www.youtube.com/watch?v=i9MHigUZKEM
https://egghead.io/courses/angularjs-fundamentals
Text Tutorials
https://docs.angularjs.org/tutorial
Try to search on google first.
If you can't understand something ask a concrete question with an example (it doesn't have to be the full code) so we can help you better.
I don't know if you have experience with Vue.js, I can tell you worse what those tutorials will explain way better. AngularJS uses a different approach than Vue, Angular 2+ or React.
Those frameworks use a component approach so you divide the app into multiple components that have properties.
Angular use an MVC-ish approach, you define modules with angular. module those modules can have external or core dependencies defined in the array.
A module can have a router, a router will define the views and the controller of each view. The views have angular directives and HTML, and the controllers have the logic.
Use one of those tutorials to learn more.
i maked one website with routes by $routeProvider, i made controller for every page and it looks like:
myApp.config(function ($routeProvider) {
$routeProvider
.when('/category/Web development', {
templateUrl: 'pages/web-dev.html',
controller: 'catCtrl'
})
.when('/category/Game Programming', {
templateUrl: 'pages/game-programming.html',
controller: 'catCtrl2'
})
myApp.controller('catCtrl', function ($scope, $http) {
$http.get("http://localhost/biblioteka/public/index/web-dev")
.then(function (response) {
$scope.books = response.data;
});
$http.get("http://localhost/biblioteka/public/category" )
.then(function (response) {
$scope.categories = response.data;
});
$scope.login = false;
$scope.hideLogin = true;
$scope.showLoginDiv = function() {
$scope.login = $scope.login? false : true;
$scope.hideLogin = $scope.hideLogin? false : true;
};
$scope.closeLoginDiv = function () {
$scope.login = false;
$scope.hideLogin = true;
};
$scope.isPassword = function () {
if ($scope.passwordValidation === "123456789") {
$scope.login = false;
$scope.hideLogin = true;
} else {
alert("Wrong password. Try again!");
};
};
});
myApp.controller('catCtrl2', function ($scope, $http) {
$http.get("http://localhost/biblioteka/public/index/game-programming")
.then(function (response) {
$scope.books = response.data;
});
$http.get("http://localhost/biblioteka/public/category")
.then(function (response) {
$scope.categories = response.data;
});
$scope.login = false;
$scope.hideLogin = true;
$scope.showLoginDiv = function() {
$scope.login = $scope.login? false : true;
$scope.hideLogin = $scope.hideLogin? false : true;
};
$scope.closeLoginDiv = function () {
$scope.login = false;
$scope.hideLogin = true;
};
$scope.isPassword = function () {
if ($scope.passwordValidation === "123456789") {
$scope.login = false;
$scope.hideLogin = true;
} else {
alert("Wrong password. Try again!");
};
};
});
as you can see, both controllers have same content, but i would like to make only one controller for different pages, any advice how i could make it? i tryed to set same controller in $routeProvider but its not working :(
I think your best approach would be something like this:
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/category/:category', {
templateUrl: function (urlattr) {
return '/category/' + urlattr.category + '.html';
},
controller: 'CategoryController',
controllerAs: 'categoryCtrl'
}).otherwise({
redirectTo: '/category/web_development'
});
}]);
myApp.controller('CategoryController', ['$routeParams', '$http', function ($routeParams, $http) {
var categoryCtrl = this;
// Use $http based on $routeParams.category
}]);
I'm having some issues transferring the modal example from the angular-ui documentation here: https://angular-ui.github.io/bootstrap/#/getting_started
I keep running into this error:
Argument 'ModalInstanceCtrl' is not a function, got undefined
controller:
(function () {
'use strict';
angular
.module('projMgrApp')
.controller('forumController', forumController)
forumController.$inject = ['$scope', '$window', '$uibModal', 'Notices'];
function forumController($scope, $window, $uibModal, Notices) {
$scope.Notices = Notices.query();
$scope.successText = "Temp Success Message";
$scope.MessageTitle = "Temp Msg Title";
$scope.MessageText = "Temp Msg Text";
angular.module('projMgrApp').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, MessageText, messageTitle) {
$scope.MessageText = MessageText;
$scope.MessageTitle = MessageTitle;
$scope.ok = function () {
$uibModalInstance.close();
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
$scope.OnAddNoticeClick = function () {
var EditNoticeModal = $uibModal.open({
templateUrl: 'add-edit-modal.html',
controller: 'ModalInstanceCtrl',
resolve: {
MessageText: function () { return $scope.MessageText },
MessageTitle: function () { return $scope.MessageTitle }
}
});
};
}
})();
the modal is spawned from a ui button that runs the OnAddNoticeClick fn.
I managed to get it to work by switching the style of controller to:
angular.module('projMgrApp')
.controller('ModalInstanceCtrl', ModalInstanceCtrl);
ModalInstanceCtrl.$inject = ['$scope', '$uibModalInstance', 'MessageText', 'MessageTitle'];
function ModalInstanceCtrl($scope, $uibModalInstance, MessageText, MessageTitle) {
$scope.MessageText = MessageText;
$scope.MessageTitle = MessageTitle;
$scope.ok = function () {
$uibModalInstance.close();
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
};
Here's my directive:
angular.module('app')
.directive('statusFilter',statusFilter);
function statusFilter() {
return {
restrict: 'E',
replace: true,
templateUrl: 'app/directives/status-filter.html',
scope: {
flags: '='
},
controller: function($scope, $element, $timeout, $document) {
function isChildElement(el) {
return $.contains($element[0], el);
}
function close(event) {
if (!isChildElement(event.target)) {
$scope.$apply(function() {
$scope.isOpen = false;
});
$document.off('mouseup', close);
}
}
function updateFlags(value) {
for (var prop in $scope.flagsClone) {
$scope.flagsClone[prop] = value;
}
}
function pullFlags() {
$scope.flagsClone = $.extend(true, {}, $scope.flags);
}
function pushFlags() {
for (var prop in $scope.flagsClone) {
$scope.flags[prop] = $scope.flagsClone[prop];
}
}
$scope.isOpen = false;
$scope.flagsClone = {};
pullFlags();
$scope.apply = function() {
pushFlags();
$scope.isOpen = false;
};
$scope.selectAll = function() {
updateFlags(true);
};
$scope.selectNone = function() {
updateFlags(false);
};
$scope.open = function() {
if (!$scope.isOpen) {
pullFlags();
$scope.isOpen = true;
$timeout(function() {
$document.on('mouseup', close);
});
}
};
}
};
}
Here's a simple test i wrote for it:
describe('status-filter directive', function() {
beforeEach(module('app'));
var template = '<status-filter flags="filters"></status-filter>';
var scope, element;
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
var ngElement = angular.element(template);
element = $compile(ngElement)(scope);
scope.$digest();
}));
it('Should open when isOpen is true', function() {
scope.open();
scope.$digest();
expect(scope.isOpen).toBe(true);
});
});
I cannot access the directive's scope no matter how i try. Like in the example above, .isolateScope(), element.scope(). With anything i try i get open() is undefined error. What is wrong in my code?
The reason why I couldn't access the scope was that I didn't create the filters variable. So this will work:
describe('status-filter directive', function() {
beforeEach(module('app'));
var template = '<status-filter flags="filters"></status-filter>';
var scope, element;
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
scope.filters = {
filter1:true;
}
var ngElement = angular.element(template);
element = $compile(ngElement)(scope);
scope.$digest();
}));
it('Should open when isOpen is true', function() {
scope.open();
scope.$digest();
expect(scope.isOpen).toBe(true);
});
});
here is the code:
(function(){
"use strict";
angular.module("dataModule")
.controller("panelController", ["$scope", "$state", "$timeout", "$modal", panelController]);
function panelController($scope, $state, $timeout, $modal){
$scope.property = "panelController";
//how do we do unit test on openCancelWarning.
//i did not find a way to get openCancelWarning function in Jasmine.
function openCancelWarning () {
var cancelModal = $modal.open({
animation: true,
backdrop: "static",
templateUrl: "pages/data/cancel-warning.html",
controller: "cancelWarningController",
size: "sm",
resolve: {
items : function() {
return {
warningTitle : "Are you Sure?",
warningMessage: "There are unsaved changes on this page. are you sure you want to navigate away from this page?Click OK to continue or Cancel to stay on this page"
};
}
}
});
return cancelModal;
}
var resultPromise = openCancelWarning();
var result;
resultPromise.result.then(function(response){
result = response;
});
}
angular.module("dataModule")
.controller("cancelWarningController", ["$scope", "$modalInstance", "items", cancelWarningController]);
function cancelWarningController($scope, $modalInstance, items){
$scope.warningTitle = items.warningTitle;
$scope.warningMessage = items.warningMessage;
$scope.cancel = function() {
$modalInstance.close(false);
};
$scope.ok = function() {
$modalInstance.close(true);
};
}
}());
here is my jasmine unit test code.
describe("Controller: panelController", function () {
beforeEach(module("dataModule"));
var panelController, scope;
var fakeModal = {
result : {
then: function(confirmCallback) {
this.confirmCallback = confirmCallback;
}
},
close: function(confirmResult) {
this.result.confirmCallback(confirmResult);
}
};
beforeEach(inject(function($modal) {
spyOn($modal, "open").andReturn(fakeModal);
}));
beforeEach(inject(function ($controller, $rootScope, _$modal_) {
scope = $rootScope.$new();
panelController = $controller("panelController", {
$scope: scope,
$modal: _$modal_
});
}));
it('test should be true', function () {
var test;
var testResult = panelController.openCancelWarning();
testResult.close(true);
testResult.then(function(response){
test=response;
});
expect(test).toBe(true);
});
});
i wrote above unit test code with the help from Mocking $modal in AngularJS unit tests
i always get below error.
TypeError: 'undefined' is not a function (evaluating 'panelController.openCancelWarning()')
could anyone help this?