Angular directive function param camel case not working - javascript

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

Related

How to declare a function in angularjs

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
}

How to change attribute on a selected directive from a controller

I build an application with interactive SVG map with angular.js
Whole app controlled by controller, svg wrapped in a directive, and every <path> in svg is a partial directive too.
When user clicked on a wall, <path> id is memorized in a custom service and next when user select a color, I need to fill this wall with that color.
The problem is that I can't access directive within a controller. I also cant share a scope with a directive because i have multiple nested directives in my controller and want to access them by id.
Maybe there is a design mistake? how can I achieve this workflow?
There is my code for controller, service and directives
ColorPicker Controller
app.controller("ColorPicker", function($scope, $timeout, appConfig, ColorService) {
$scope.colors = [];
$scope.currentColorSet = 0;
$scope.svgTemplateUrl = appConfig.arSvg[$scope.$parent.roomType.id][$scope.$parent.roomStyle.id] + 'over.svg';
$scope.maxColorSet = Math.max.apply(Math, jsondata.roomtype[$scope.$parent.roomType.id].data.roomstyle[$scope.$parent.roomStyle.id].colors.map(function(color) {
return color.color.group;
}));
$scope.sliderConfig = {
min: 0,
max: $scope.maxColorSet,
step: 1
}
$scope.emptyColors = ( ColorService.getColors().length === 0 );
$scope.currentProps = {};
$scope.applyColor = function(color) {
console.log($scope.currentProps);
//**here I need to set fill with selected color to selected directive**
}
$scope.prevColorSet = function(){
if($scope.currentColorSet > 0) {
$scope.currentColorSet--;
generateColorSet($scope.currentColorSet);
}
}
$scope.nextColorSet = function(){
if($scope.currentColorSet < $scope.maxColorSet) {
$scope.currentColorSet++;
generateColorSet($scope.currentColorSet);
}
}
generateColorSet = function(setIndex){
$scope.colors = [];
for(var i = 0; i < jsondata.roomtype[$scope.$parent.roomType.id].data.roomstyle[$scope.$parent.roomStyle.id].colors.length; i++){
if(jsondata.roomtype[$scope.$parent.roomType.id].data.roomstyle[$scope.$parent.roomStyle.id].colors[i].color.group == setIndex) {
$scope.colors.push(jsondata.roomtype[$scope.$parent.roomType.id].data.roomstyle[$scope.$parent.roomStyle.id].colors[i].color)
}
}
}
generateColorSet($scope.currentColorSet);
$scope.$watch("currentColorSet", function(newValue, oldValue) {
generateColorSet($scope.currentColorSet);
});
});
Directive for whole SVG
app.directive('svgmap', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var svg = $(element).find('svg');
svg.removeAttr('xmlns:a');
svg.attr('width', '869px');
svg.attr('height', '489px');
element.append(svg);
var regions = element[0].querySelectorAll('path');
angular.forEach(regions, function (path, key) {
var regionElement = angular.element(path);
regionElement.attr("region", "");
$compile(regionElement)(scope);
});
},
}
}]);
Directive for region (wall)
app.directive('region', ['$compile','ColorService','$timeout', function ($compile, ColorService, $timeout) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.properties = {
elementId : element.attr("id"),
stroke: '',
fill: '#fff'
};
scope.regionClick = function () {
scope.currentProps = scope.properties;
if(ColorService.selectedRegion != scope.properties.elementId) {
scope.properties.stroke = '#e5514e';
ColorService.selectedRegion = scope.properties.elementId;
} else {
scope.properties.stroke = '';
ColorService.selectedRegion = '';
}
console.log('click: ' + scope.properties.elementId + ' : ' + scope.properties.stroke);
};
scope.setStroke = function () {
scope.stroke = '#e5514e';
};
scope.removeStroke = function() {
if(ColorService.selectedRegion != scope.properties.elementId) {
scope.properties.stroke = '';
}
//console.log('enter: ' + scope.elementId + ' : ' + scope.stroke);
};
scope.removeColor = function() {
console.log('removed');
scope.properties.fill = '#fff';
ColorService.remove(scope.properties.elementId);
};
ColorService.getColors().forEach(function(item) {
if(item.id === scope.properties.elementId) {
scope.properties.fill = item.info.val;
}
});
element.attr("ng-click", "regionClick()");
element.attr("ng-attr-stroke", "{{properties.stroke}}");
element.attr("ng-attr-fill", "{{properties.fill}}");
element.attr("ng-mouseenter", "setStroke()");
element.attr("ng-mouseleave", "removeStroke()");
element.attr("ng-right-click", "removeColor()");
element.after('<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />');
element.removeAttr("region");
$compile(element)(scope);
}
}
}]);

Promise not resolving in custom TypeAhead directive

I edited the TypeAhead directive that is part of Angular UI for AngularJS so it will only give suggestions based on the most recent word, delimited by space (" ").
I intend to use it to for something like a query builder, dynamically giving suggestions based on surrounding syntax. This works as expected for the first word, but once we get to the second word, the promise does not resolve anymore for some reason. The value of inputValue is correct and as expected, but the code inside
$q.when(parserResult.source(originalScope, locals)).then(function (matches) {
does not appear to get run. Please advise.
My code (exactly the same as original except for I added a function called getLastWord that truncates the current expression :
angular.module('customTypeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])
.factory('customTypeaheadParser', ['$parse', function ($parse) {
// 00000111000000000000022200000000000000003333333333333330000000000044000
var TYPEAHEAD_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w\d]*))\s+in\s+([\s\S]+?)$/;
return {
parse: function (input) {
var match = input.match(TYPEAHEAD_REGEXP);
if (!match) {
throw new Error(
'Expected customTypeahead specification in form of "_modelValue_ (as _label_)? for _item_ in _collection_"' +
' but got "' + input + '".');
}
return {
itemName: match[3],
source: $parse(match[4]),
viewMapper: $parse(match[2] || match[1]),
modelMapper: $parse(match[1])
};
}
};
}])
.directive('customTypeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$rootScope', '$position', 'customTypeaheadParser',
function ($compile, $parse, $q, $timeout, $document, $rootScope, $position, customTypeaheadParser) {
var HOT_KEYS = [9, 13, 27, 38, 40];
return {
require: 'ngModel',
link: function (originalScope, element, attrs, modelCtrl) {
//SUPPORTED ATTRIBUTES (OPTIONS)
//minimal no of characters that needs to be entered before customTypeahead kicks-in
var minLength = originalScope.$eval(attrs.customTypeaheadMinLength);
if (!minLength && minLength !== 0) {
minLength = 0;
}
//minimal wait time after last character typed before customTypeahead kicks-in
var waitTime = originalScope.$eval(attrs.customTypeaheadWaitMs) || 0;
//should it restrict model values to the ones selected from the popup only?
var isEditable = originalScope.$eval(attrs.customTypeaheadEditable) !== false;
//binding to a variable that indicates if matches are being retrieved asynchronously
var isLoadingSetter = $parse(attrs.customTypeaheadLoading).assign || angular.noop;
//a callback executed when a match is selected
var onSelectCallback = $parse(attrs.customTypeaheadOnSelect);
var inputFormatter = attrs.customTypeaheadInputFormatter ? $parse(attrs.customTypeaheadInputFormatter) : undefined;
var appendToBody = attrs.customTypeaheadAppendToBody ? originalScope.$eval(attrs.customTypeaheadAppendToBody) : false;
var focusFirst = originalScope.$eval(attrs.customTypeaheadFocusFirst) !== false;
//INTERNAL VARIABLES
//model setter executed upon match selection
var $setModelValue = $parse(attrs.ngModel).assign;
//expressions used by customTypeahead
var parserResult = customTypeaheadParser.parse(attrs.customTypeahead);
var hasFocus;
//create a child scope for the customTypeahead directive so we are not polluting original scope
//with customTypeahead-specific data (matches, query etc.)
var scope = originalScope.$new();
originalScope.$on('$destroy', function () {
scope.$destroy();
});
// WAI-ARIA
var popupId = 'customTypeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);
element.attr({
'aria-autocomplete': 'list',
'aria-expanded': false,
'aria-owns': popupId
});
//pop-up element used to display matches
var popUpEl = angular.element('<div custom-typeahead-popup></div>');
popUpEl.attr({
id: popupId,
matches: 'matches',
active: 'activeIdx',
select: 'select(activeIdx)',
query: 'query',
position: 'position'
});
//custom item template
if (angular.isDefined(attrs.customTypeaheadTemplateUrl)) {
popUpEl.attr('template-url', attrs.customTypeaheadTemplateUrl);
}
var resetMatches = function () {
scope.matches = [];
scope.activeIdx = -1;
element.attr('aria-expanded', false);
};
var getMatchId = function (index) {
return popupId + '-option-' + index;
};
// Indicate that the specified match is the active (pre-selected) item in the list owned by this customTypeahead.
// This attribute is added or removed automatically when the `activeIdx` changes.
scope.$watch('activeIdx', function (index) {
if (index < 0) {
element.removeAttr('aria-activedescendant');
} else {
element.attr('aria-activedescendant', getMatchId(index));
}
});
var getLastWord = function (expression) {
if (expression === "") {
return "";
}
var temp = expression.split(" ");
return temp[temp.length - 1];
};
var getMatchesAsync = function (inputValue) {
inputValue = getLastWord(inputValue);
var locals = {$viewValue: inputValue};
isLoadingSetter(originalScope, true);
$q.when(parserResult.source(originalScope, locals)).then(function (matches) {
//it might happen that several async queries were in progress if a user were typing fast
//but we are interested only in responses that correspond to the current view value
var onCurrentRequest = (inputValue === modelCtrl.$viewValue);
if (onCurrentRequest && hasFocus) {
if (matches && matches.length > 0) {
scope.activeIdx = focusFirst ? 0 : -1;
scope.matches.length = 0;
//transform labels
for (var i = 0; i < matches.length; i++) {
locals[parserResult.itemName] = matches[i];
scope.matches.push({
id: getMatchId(i),
label: parserResult.viewMapper(scope, locals),
model: matches[i]
});
}
scope.query = inputValue;
//position pop-up with matches - we need to re-calculate its position each time we are opening a window
//with matches as a pop-up might be absolute-positioned and position of an input might have changed on a page
//due to other elements being rendered
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight');
element.attr('aria-expanded', true);
} else {
resetMatches();
}
}
if (onCurrentRequest) {
isLoadingSetter(originalScope, false);
}
}, function () {
resetMatches();
isLoadingSetter(originalScope, false);
});
};
resetMatches();
//we need to propagate user's query so we can highlight matches
scope.query = undefined;
//Declare the timeout promise var outside the function scope so that stacked calls can be cancelled later
var timeoutPromise;
var scheduleSearchWithTimeout = function (inputValue) {
timeoutPromise = $timeout(function () {
getMatchesAsync(inputValue);
}, waitTime);
};
var cancelPreviousTimeout = function () {
if (timeoutPromise) {
$timeout.cancel(timeoutPromise);
}
};
//plug into $parsers pipeline to open a customTypeahead on view changes initiated from DOM
//$parsers kick-in on all the changes coming from the view as well as manually triggered by $setViewValue
modelCtrl.$parsers.unshift(function (inputValue) {
inputValue = getLastWord(inputValue);
hasFocus = true;
if (minLength === 0 || inputValue && inputValue.length >= minLength) {
if (waitTime > 0) {
cancelPreviousTimeout();
scheduleSearchWithTimeout(inputValue);
} else {
getMatchesAsync(inputValue);
}
} else {
isLoadingSetter(originalScope, false);
cancelPreviousTimeout();
resetMatches();
}
if (isEditable) {
return inputValue;
} else {
if (!inputValue) {
// Reset in case user had typed something previously.
modelCtrl.$setValidity('editable', true);
return inputValue;
} else {
modelCtrl.$setValidity('editable', false);
return undefined;
}
}
});
modelCtrl.$formatters.push(function (modelValue) {
var candidateViewValue, emptyViewValue;
var locals = {};
// The validity may be set to false via $parsers (see above) if
// the model is restricted to selected values. If the model
// is set manually it is considered to be valid.
if (!isEditable) {
modelCtrl.$setValidity('editable', true);
}
if (inputFormatter) {
locals.$model = modelValue;
return inputFormatter(originalScope, locals);
} else {
//it might happen that we don't have enough info to properly render input value
//we need to check for this situation and simply return model value if we can't apply custom formatting
locals[parserResult.itemName] = modelValue;
candidateViewValue = parserResult.viewMapper(originalScope, locals);
locals[parserResult.itemName] = undefined;
emptyViewValue = parserResult.viewMapper(originalScope, locals);
return candidateViewValue !== emptyViewValue ? candidateViewValue : modelValue;
}
});
scope.select = function (activeIdx) {
//called from within the $digest() cycle
var locals = {};
var model, item;
locals[parserResult.itemName] = item = scope.matches[activeIdx].model;
model = parserResult.modelMapper(originalScope, locals);
$setModelValue(originalScope, model);
modelCtrl.$setValidity('editable', true);
modelCtrl.$setValidity('parse', true);
onSelectCallback(originalScope, {
$item: item,
$model: model,
$label: parserResult.viewMapper(originalScope, locals)
});
resetMatches();
//return focus to the input element if a match was selected via a mouse click event
// use timeout to avoid $rootScope:inprog error
$timeout(function () {
element[0].focus();
}, 0, false);
};
//bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)
element.bind('keydown', function (evt) {
//customTypeahead is open and an "interesting" key was pressed
if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {
return;
}
// if there's nothing selected (i.e. focusFirst) and enter is hit, don't do anything
if (scope.activeIdx == -1 && (evt.which === 13 || evt.which === 9)) {
return;
}
evt.preventDefault();
if (evt.which === 40) {
scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;
scope.$digest();
} else if (evt.which === 38) {
scope.activeIdx = (scope.activeIdx > 0 ? scope.activeIdx : scope.matches.length) - 1;
scope.$digest();
} else if (evt.which === 13 || evt.which === 9) {
scope.$apply(function () {
scope.select(scope.activeIdx);
});
} else if (evt.which === 27) {
evt.stopPropagation();
resetMatches();
scope.$digest();
}
});
element.bind('blur', function (evt) {
hasFocus = false;
});
// Keep reference to click handler to unbind it.
var dismissClickHandler = function (evt) {
if (element[0] !== evt.target) {
resetMatches();
if (!$rootScope.$$phase) {
scope.$digest();
}
}
};
$document.bind('click', dismissClickHandler);
originalScope.$on('$destroy', function () {
$document.unbind('click', dismissClickHandler);
if (appendToBody) {
$popup.remove();
}
// Prevent jQuery cache memory leak
popUpEl.remove();
});
var $popup = $compile(popUpEl)(scope);
if (appendToBody) {
$document.find('body').append($popup);
} else {
element.after($popup);
}
}
};
}])
.directive('customTypeaheadPopup', function () {
return {
restrict: 'EA',
scope: {
matches: '=',
query: '=',
active: '=',
position: '&',
select: '&'
},
replace: true,
templateUrl: 'html/templates/custom-typeahead-popup.html',
link: function (scope, element, attrs) {
scope.templateUrl = attrs.templateUrl;
scope.isOpen = function () {
return scope.matches.length > 0;
};
scope.isActive = function (matchIdx) {
return scope.active == matchIdx;
};
scope.selectActive = function (matchIdx) {
scope.active = matchIdx;
};
scope.selectMatch = function (activeIdx) {
scope.select({activeIdx: activeIdx});
};
}
};
})
.directive('customTypeaheadMatch', ['$templateRequest', '$compile', '$parse', function ($templateRequest, $compile, $parse) {
return {
restrict: 'EA',
scope: {
index: '=',
match: '=',
query: '='
},
link: function (scope, element, attrs) {
var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'html/templates/custom-typeahead-match.html';
$templateRequest(tplUrl).then(function (tplContent) {
$compile(tplContent.trim())(scope, function (clonedElement) {
element.replaceWith(clonedElement);
});
});
}
};
}])
.filter('customTypeaheadHighlight', function () {
function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function (matchItem, query) {
return query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem;
};
});

Directive that run after ng-repeat

I have similar problem with this one Calling a function when ng-repeat has finished but I have directive and ng-repeat inside.
<my-dropdown>
<li ng-repeat="item in items"><a>{{item.text}}</a></li>
</my-dropdown>
In my dropdown I have ng-transclude in two places (one for a list and one for caption) and I need to add class ng-hide to all items except one using jQuery. So I need to have the code that will run after ng-repeat. I've try to set priority in my directive to 2000 or 0 (ngRepeat have 1000) but this doesn't work. I've got one item when I run element.find('li');
return {
restrict: 'E',
require: '?ngModel',
template: ['<div class="btn-group dropdown-button">',
' <div class="btn caption" ng-transclude></div>',
' <button class="btn dropdown-toggle" data-toggle="dropdown">',
' <span class="caret"></span>',
' </button>',
' <ul class="dropdown-menu" ng-transclude></ul>',
'</div>'].join('\x0D'), // newline - peach replace newlines, gods only know why
transclude: true,
replace: true,
compile: function(element, attrs, transclude) {
// I've used compile because I wante to test the transclude function
return function(scope, element, attrs, ngModelCtrl) {
element.find('.caption li').attr('ng-hide', 'true');
var selected_index = 0;
function setValue(item) {
var value = item.attr('value');
ngModelCtrl.$setViewValue(value ? $interpolate(value)(scope) : item.index());
}
var caption = element.find('.caption');
function update() {
// for model with ng-repeat it return 1 item
console.log(attrs.ngModel + ' ' + caption.find('li').length);
caption.find('li').removeClass('ng-hide').not(':eq(' + selected_index + ')').addClass('ng-hide');
}
if (ngModelCtrl) {
element.on('click', 'ul li', function() {
var self = $(this);
selected_index = self.index();
scope.$apply(function() {
setValue(self);
});
var selected = self.attr('selected');
if (selected) {
scope.$eval(selected);
}
});
if (!ngModelCtrl.$viewValue && attrs.placeholder) {
$('<li>' + attrs.placeholder + '</li>').appendTo(caption);
selected_index = caption.find('li').length-1;
} else {
selected_index = ngModelCtrl.$viewValue || 0;
}
setValue(element.find('ul li:eq(' + selected_index + ')'));
ngModelCtrl.$viewChangeListeners.push(function() {
scope.$eval(attrs.ngChange);
update();
});
ngModelCtrl.$render = function() {
if (!ngModelCtrl.$modelValue) {
selected_index = 0;
update();
} else {
$(element).find('ul li').each(function(i) {
var self = $(this);
var value = self.attr('value');
if (value && ngModelCtrl.$modelValue == $interpolate(value)(scope) ||
ngModelCtrl.$modelValue == i) {
selected_index = i;
update();
return false;
}
});
}
};
}
update();
};
}
}

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