How to declare a function in angularjs - javascript

I have a function and i did it in this way
JS :
function updateInstitution (isValid) {alert('hi')
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.institutionForm');
return false;
}
var data = JSON.stringify(vm.institution);
httpService.put('institutions/' + vm.institution_id, data).then(function (results) {
if (results && results.data && results.data.details) {
vm.institution = results.data.details;
formInstitutionData('profile');
commonService.showNotification('success', 'Institution Details updated successfully!');
$('#institutionModal').modal('hide');
}
});
}
}
vm.updateInstitution = updateInstitution;
Html :
<button type="button" class="btn btn-blue" ng-click="vm.updateInstitution(vm.form.institutionForm.$valid)" ng-bind="field.saveText"></button>
But i am getting the error as
updateInstitution is not defined
Can anyone please suggest help.Thanks.
JS :
(function () {
'use strict';
// Institutions controller
angular
.module('institutions')
.controller('InstitutionsController', InstitutionsController);
InstitutionsController.$inject = ['$scope', '$state', '$window', '$timeout', 'httpService', 'Authentication', 'commonService'];
function active() {
httpService.get('institutions/' + vm.institution_id).then(function (results) {
if (results && results.data && results.data.details) {
vm.institutionCopyData = angular.copy(results.data.details);
formInstitutionData('all');
}
});
}
$scope.editInstitutionModal = function (type) {
$scope.field = {};
$scope.showInstitutionModal = false;
if (type === 'basicedit') {
$scope.field.field_type = 'edit-institution.form.client';
$scope.field.formName = 'Edit institution (' + vm.institutionObj.name + ')';
$scope.field.saveText = 'Update';
}
if(type === 'general'){
$scope.field.field_type = 'add-general.form.client';
$scope.field.formName = 'General Info';
$scope.field.saveText = 'Save';
}
$timeout(function () {
$scope.showInstitutionModal = true;
$('#institutionModal').modal('show');
$scope.$apply();
}, 10);
};
function updateInstitution (isValid) {alert('hi')
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.institutionForm');
return false;
}
var data = JSON.stringify(vm.institution);
httpService.put('institutions/' + vm.institution_id, data).then(function (results) {
if (results && results.data && results.data.details) {
vm.institution = results.data.details;
formInstitutionData('profile');
commonService.showNotification('success', 'Institution Details updated successfully!');
$('#institutionModal').modal('hide');
}
});
}
}
}
}());
But i am getting the error as
updateInstitution is not defined
Can anyone please suggest help.Thanks.
But i am getting the error as
updateInstitution is not defined
Can anyone please suggest help.Thanks.

You should declare the following in your controller:
var vm = this;
vm.updateInstitution = updateInstitution;

you use $scope.updateInstitution instead of function updateInstitution() , because communication bridge between html and controller is $scope,
or for use vm.function you defined $scope.vm

$scope.updateInstitution = function(){
//Your code
}

Related

ngToast returns undefined when used inside a service

I am trying to create a simple notification system using ngToast through this documentation - http://tamerayd.in/ngToast/. Everything seems to work correctly when using it inside my module(login-flow) but if I'm trying to pass it to a service ($notify) it returns undefined in the console. Thing is that the first time I used this service as a test, it worked. Once I customized it for my needs, the problem appeared. Note that I'm not that good with angularjs and I'm learning it while working on this project. If you notice anything odd or not a "best practice", please, do tell (this part might be a bit offtopic so ignore it if you feel like it).
I've already tried removing any code that felt redundant and also changing parameters orders but the result is the same. Note that this works when using ngToast as a dependency inside the "login-flow" controller but as long as I pass it to the "$notify" service, the problem starts to occur.
app module: index-globals.js
const licentaApp = angular.module("licenta-app", ["ngToast"]);
licentaApp.run(($rootScope, $location) => {
$rootScope.$on('$locationChangeSuccess', function() {
return $location.$$hash;
});
}).controller("app", ($scope, $rootScope, $location) => {
$scope.hash = "";
$rootScope.$on('$locationChangeSuccess', function() {
$scope.hash = $location.$$hash;
});
});
index-login-controller.js - controller which calls the $notify service
licentaApp.controller("login-flow", ($scope, $http, $notify,ngToast) => {
// $scope.username = "admin#admin.com";
// $scope.password = "pass";
$scope.isLoading = false;
$scope.login = () => {
$scope.isLoading = true;
$scope.loading_class = "spinner-border text-light";
$scope.login_text = "";
$http({
url: "attempt-login",
method: "GET",
params: {
username: $scope.email,
password: $scope.password
},
headers: {
"Content-Type": "text/plain"
}
}).then(function(result) {
console.log(ngToast)
if (result.data !== "no_result") {
$notify.displayNotification("Bine ați venit!",ngToast);
location.hash = "profil";
} else {
$notify.displayNotification("Datele de logare nu au fost introduse corect.", ngToast,isError);
}
$scope.isLoading = false;
}).catch(err => {
$notify.displayNotification("A aparut o eroare: " + err);
$scope.isLoading = false;
});
}
$scope.forgotPass = () => {
location.hash = "uitat_parola";
}
});
licentaApp.controller("forgot-pass-flow", ($scope, $rootScope, $location, $http, $timeout, $notify) => {
function verifyCNP(cnp) {
let sum = 0;
controlNumber = "279146358279";
if (cnp.length !== 13) {
$notify.displayNotification($rootScope, $timeout, "Unul dintre codurile numerice este incorect.", true);
return false;
} else {
for (let i = 0; i < 12; i++) {
sum += parseInt(cnp[i]) * parseInt(controlNumber[i]);
}
let controlDigit = sum % 11 === 10 ? 1 : sum % 11;
if (controlDigit !== parseInt(cnp[12])) {
$notify.displayNotification($rootScope, $timeout, "Unul dintre codurile numerice este incorect.", true);
return false;
} else {
return true;
}
}
}
$scope.isLoading = false;
$scope.back = () => {
location.hash = "";
}
$scope.reset = () => {
if ($scope.cnp && $scope.cnp_repeat) {
if (verifyCNP($scope.cnp) === false || verifyCNP($scope.cnp_repeat) === false) {
return;
} else if (!$scope.email || !$scope.email.match(/([A-Z0-9!#$%&'*+-/=?^_`{|}~.])/gi)) {
$notify.displayNotification($rootScope, $timeout, "Email-ul este incorect.", true);
} else {
alert("TEST")
}
} else {
$notify.displayNotification($rootScope, $timeout, "Unul dintre câmpurile de CNP nu a fost completat.", true);
}
}
});
$notify.js - notification service
licentaApp
.service("$notify", function () {
this.displayNotification = (message, ngToast,isError) => {
ngToast.create({
className : isError ? "danger" : "success",
content : message,
dismissOnClick : true,
animation : "slide",
timeout : 5000
});
// console.log(ngToast)
}
});
Nvm - it was something really minor. I was actually sending "isError" as a parameter to the notification system instead of assigning it a value. This feels soooo obvious that I actually feel bad about asking question in the first place.

Angular directive function param camel case not working

I have an Angular 1.5.8 directive with isolated scope and two functions being passed in. I have found that when the names of these functions are all lower case that they work correctly but if they are camelCased then they do not work.
Note that I am talking about the value of the param not the param name itself. here's the html that uses the directive:
<buttons-radio model="contactInformationAcceptable" disabled="approved" callback="personalapprovalfieldchanged()" focus="focuscallback($event)"></buttons-radio>
Note the case of the callback and focus values. If I change these to camel case (and change the function definitions in the parent scope) then they don't work.
Here is the directive:
angular.module("manageApp").directive('buttonsRadio', ['$timeout', function ($timeout) {
return {
restrict: 'E',
scope: {
model: '=',
disabled: '=',
callback: '&',
focus: '&'
},
template: '<div class="form-group yesorno"> ' +
' <div class="col-xs-12">' +
' <button type="button" class="btn btn-success" ng-disabled="disabled" ng-class="{active: yesValue}" ng-click="clickYes()" ng-focus="localFocus($event)">Yes</button>' +
' <button type="button" class="btn btn-danger" ng-disabled="disabled" ng-class="{active: noValue}" ng-click="clickNo()" ng-focus="localFocus($event)">No</button>' +
' </div>' +
'</div>',
controller: function ($scope) {
$scope.$watch('model', function (value) {
if (value) {
if (value == 0) {
$scope.yesValue = false;
$scope.noValue = false;
}
if (value == 1) {
$scope.yesValue = true;
$scope.noValue = false;
}
if (value == 2) {
$scope.yesValue = false;
$scope.noValue = true;
}
}
});
$scope.localFocus = function ($event) {
$scope.focus({ $event: $event });
}
$scope.performCallback = function () {
$timeout(function () {
$scope.callback();
});
}
$scope.yesValue = false;
$scope.noValue = false;
$scope.clickYes = function () {
$scope.yesValue = !$scope.yesValue;
if ($scope.yesValue) {
$scope.noValue = false;
$scope.model = 1;
} else {
$scope.model = 0;
}
$scope.performCallback();
}
$scope.clickNo = function () {
$scope.noValue = !$scope.noValue;
if ($scope.noValue) {
$scope.yesValue = false;
$scope.model = 2;
} else {
$scope.model = 0;
}
$scope.performCallback();
}
}
}
}]);
Edit: Here is the parent controller that has the function I need to use:
angular.module("manageApp").controller('approvalPersonalController', ['$scope', '$http',
function ($scope, $http) {
//personalApprovalFieldChanged personalapprovalfieldchanged
$scope.personalapprovalfieldchanged = function () {
//a field has changed so save them all
console.log('field has changed - do something');
};
}]);
I am confused as to why this is as I have been through a Pluralsight course on directives and the camel case works OK in the plunks that I have created from the course but not in this real world example.
It does work (calls the correct functions at the correct times) but I would like to use camel case for the function names if possible.
Thanks

How to change controller variable in service angular?

This's my service. I've got variable isPolygonDrawingEnded there.
angular
.module('gillie.clients.app')
.service('mapDrawingService', mapDrawingService);
mapDrawingService.$inject = ['$ngBootbox', '$translate', 'fitPolygonService', 'mapCommonService'];
function mapDrawingService($ngBootbox, $translate, fitPolygonService, mapCommonService) {
var self = this;
var map;
var polygonFeatures;
var stopDrawingAction;
var isPolygonDrawingEnded = false;
var isDrawingMode = true;
self.startNewPolygonDrawing = function (afterDrowed) {
fitPolygonService.suggestPoint(isDrawingMode);
var modify = createModifyInteractionToPolygonFeatures();
var draw = createDrawInteraction();
attachDrawEvents(draw, afterDrowed);
map.addInteraction(draw);
stopDrawingAction = function() {
map.removeInteraction(draw);
map.removeInteraction(modify);
};
};
var attachDrawEvents = function (draw, afterDrowed) {
draw.on('drawend', function (e) {
e.preventDefault();
afterDrowed();
isPolygonDrawingEnded = true;
if (fitPolygonService.isPolygonsExist()) {
var geometry = e.feature.getGeometry();
e.feature.setGeometry(fitPolygonService.fitPolygon(geometry));
}
});
}
This is my controller. Here I need to change $scope.showCountButton when mapDrawingService.isPolygonDrawingEnded == true. So how can I know that value in service is changed ?
angular
.module('gillie.clients.app')
.controller('regionController', regionController);
regionController.$inject = ['$q', '$filter', '$scope', '$ngBootbox', '$translate', 'regionService', 'mapService', 'mapDrawingService', 'modalService', 'regionCommonService', 'alertService', 'nominatimCommonService', 'populationService', 'provinceCommonService', 'provinceService', 'rx'];
function regionController($q, $filter, $scope, $ngBootbox, $translate, regionService, mapService, mapDrawingService, modalService, regionCommonService, alertService, nominatimCommonService, populationService, provinceCommonService, provinceService, rx) {
$scope.showCountButton = false;
$scope.startRegionSelection = function (region) {
$scope.isSavingAvailable = true;
$scope.showCountButton = false;
if (currentEditingRegion && region && currentEditingRegion.Id === region.Id) {
return;
}
if(region)
mapService.clearRegion(region);
if (currentEditingRegion && !region) {
mapDrawingService.continuePolygonDrawing();
return;
}
if (region) {
mapDrawingService.stopPolygonDrawing();
mapDrawingService.clearMap();
currentEditingRegion = region;
mapDrawingService.startExistPolygonDrawing(region.Name, region.CoordinatesJson);
return;
}
mapDrawingService.startNewPolygonDrawing(function () {
$scope.showCountButton = true
});
};
When I use mapDrawingService.startNewPolygonDrawing function - the value of showCountButton changes but view doesn't. $scope.$apply produces this exception:
[$rootScope:inprog] $digest already in progress
When you are passing the callback function it is no longer in the scope of the controller which is why the view is not updating. You can use promises instead since you are asynchronous draw event.
Service
mapDrawingService.$inject = ['$q', '$ngBootbox', '$translate', 'fitPolygonService', 'mapCommonService'];
function mapDrawingService($q, $ngBootbox, $translate, fitPolygonService, mapCommonService) {
var self = this;
var map;
var polygonFeatures;
var stopDrawingAction;
var isPolygonDrawingEnded = false;
var isDrawingMode = true;
self.startNewPolygonDrawing = function() {
fitPolygonService.suggestPoint(isDrawingMode);
var modify = createModifyInteractionToPolygonFeatures();
var draw = createDrawInteraction();
var promiseObj = attachDrawEvents(draw);
map.addInteraction(draw);
stopDrawingAction = function() {
map.removeInteraction(draw);
map.removeInteraction(modify);
};
return promiseObj;
};
var attachDrawEvents = function(draw) {
return $q(function(resolve, reject) {
draw.on('drawend', function(e) {
e.preventDefault();
if (fitPolygonService.isPolygonsExist()) {
var geometry = e.feature.getGeometry();
e.feature.setGeometry(fitPolygonService.fitPolygon(geometry));
}
resolve();
});
});
}
Controller
mapDrawingService.startNewPolygonDrawing().then(function() {
$scope.showCountButton = true
});

How can get data to my page controller js from another controller js used in Master Page using angularjs?

Master Page Controllerjs:
I am want to get following categoryId from event fired by $scope.braodcast on my event(inner) page.
$scope.RedirectToEventPage = function (categoryId) {
var url = window.location.host + '/events';
if (categoryId == 'ALL') {
$rootscope.$broadcast('CategoryId', 0);
}
else {
$scope.$broadcast('CategoryId', categoryId);
}
window.location = '/events';
};
Event Page Controllerjs:
$scope.on displaying 'undefined' with console.
knrApp.controller("EventCtrl", function ($scope, eventFactory, $rootscope) {
$(document).ready(function () {
$rootscope.$on('CategoryId', function (event, data) {
if (data == null || data === undefined || data == '') {
$scope.categoryId = 0;
}
else {
$scope.categoryId = data;
}
});
// $scope.categoryId = 0;
console.log($scope.categoryId);
$scope.GetAllEventData($scope.categoryId);
});
}

Variable coming back undefined into the same scope in AngularJS

Given the following code, I'm finding that once the loadDetails function (the last one) is being triggered, the ID variable comes back undefined, as on the other functions is coming back correctly.
Did I miss something?
function Ctrl($scope, $http) {
var search = function(name) {
if (name) {
$http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=7', {ignoreLoadingBar: true}).
success(function(data3) {
$scope.clicked = false;
$scope.results = data3.results;
});
}
$scope.reset = function () {
$scope.sliding = false;
$scope.name = undefined;
}
}
$scope.$watch('name', search, true);
$scope.getDetails = function (id) {
$http.get('http://api.discogs.com/artists/' + id).
success(function(data) {
$scope.artist = data;
});
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=8').
success(function(data2) {
$scope.releases = data2.releases;
});
$scope.$watch(function() {
return $scope.artist;
}, function() {
var pos = $scope.artist.name.toLowerCase().indexOf(', the');
if (pos != -1) {
$scope.artist.name = 'The ' + $scope.artist.name.slice(0, pos);
}
});
var _page = 0;
$scope.releases = [];
$scope.loadDetails = function(id) {
_page++;
console.log(_page);
$http.get('http://api.discogs.com/artists/' + id + '/releases?page=' + _page + '&per_page=12').then(function(data2) {
$scope.releases = data2.releases;
});
};
$scope.clicked = true;
$scope.sliding = true;
}
EDIT: Here's my view code:
<div class="infinite" infinite-scroll="loadDetails(artist.id)">
<div class="col-xs-3 col-md-3 release" ng-controller="ImageCtrl" release="release" ng-repeat="release in releases | filter:album | filter:year" the-directive position="{{ $index + 1 }}" last="{{ $last }}">
<img class="img-responsive" ng-src="{{image}}"/> {{release.title | characters:45}}
</div>
<div style='clear: both;'></div>
</div>
And the ng-Infinite-Scroll script that triggers the function when the containing div reaches the bottom:
/* ng-infinite-scroll - v1.0.0 - 2013-02-23 */
var mod;
mod = angular.module('infinite-scroll', []);
mod.directive('infiniteScroll', [
'$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) {
return {
link: function(scope, elem, attrs) {
var checkWhenEnabled, handler, scrollDistance, scrollEnabled;
$window = angular.element($window);
scrollDistance = 0;
if (attrs.infiniteScrollDistance != null) {
scope.$watch(attrs.infiniteScrollDistance, function(value) {
return scrollDistance = parseInt(value, 10);
});
}
scrollEnabled = true;
checkWhenEnabled = false;
if (attrs.infiniteScrollDisabled != null) {
scope.$watch(attrs.infiniteScrollDisabled, function(value) {
scrollEnabled = !value;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return handler();
}
});
}
handler = function() {
var elementBottom, remaining, shouldScroll, windowBottom;
windowBottom = $window.height() + $window.scrollTop();
elementBottom = elem.offset().top + elem.height();
remaining = elementBottom - windowBottom;
shouldScroll = remaining <= $window.height() * scrollDistance;
if (shouldScroll && scrollEnabled) {
if ($rootScope.$$phase) {
return scope.$eval(attrs.infiniteScroll);
} else {
return scope.$apply(attrs.infiniteScroll);
}
} else if (shouldScroll) {
return checkWhenEnabled = true;
}
};
$window.on('scroll', handler);
scope.$on('$destroy', function() {
return $window.off('scroll', handler);
});
return $timeout((function() {
if (attrs.infiniteScrollImmediateCheck) {
if (scope.$eval(attrs.infiniteScrollImmediateCheck)) {
return handler();
}
} else {
return handler();
}
}), 0);
}
};
}
]);
rSo from what I read I understand you problem as in loadDetails() the id parameter is undefined. Where is loadDetails() called from? I assume its being called from the view. Are you passing this param in when it is being called? For ex:
<button ng-click="loadDetails('myId')">Load Details</button>
I would say your issue is you are not passing the param to this function. It would be helpful if you posted the view associated with this controller.

Categories