ngMessages with custom validator in parent controller - angularjs

I'm trying to figure out how to wire up a custom validator with ngMessages that has access to the parent scope. I have an input field for an address and onBlur I want to do a geolocate of the address and update the position of a marker on a map (by setting two variables on the controllers this).
Custom validator examples use directives (and I have followed those for a basic example) but can't move from their to geolocation, as I'm struggling with Directive to parent Controller communication in the context of ES6, ControllerAs,...:
I've started off trying to access the parent controller from the link function with scope.$parent (How to access parent scope from within a custom directive *with own scope* in AngularJS?) but I'm using ES6 classes and it just did not seem to work.
now I'm thinking about passing in the parent function to the Directive, but the function is complaining that it cannot find elements of the controller's normal scope, so that means it cannot update the marker's position.
Grateful for advice on wiring this up.
Here's where I got to in the second instance
var checkAddressDir = function($timeout) {
return {
require : 'ngModel',
scope: {
geolookup: '&'
},
link : function(scope, element, attrs, ngModel) {
function setAsLoading(bool) {
ngModel.$setValidity('recordLoading', !bool);
}
ngModel.$parsers.push(function(value) {
if(!value || value.length == 0) return;
setAsLoading(true);
scope.geolookup()(value)
// scope.$parent.findAddress()
.then( res => {
// I'll use res to update ngModel.$setValidity
console.log(res);
setAsLoading(false);
});
// THE FOLLOWING SERVED TO GET ME STARTED
// $timeout(function() {
// console.log("timeout");
// setAsLoading(false);
// }, 1000);
return value;
})
}
}
}
And this is the controller function I need to be able to use with the controller's scope
findAddress(address) {
return this.$q( (resolve, reject) => {
mygeocoder.geocode(myOptions, (res, stat) => {
if (stat === google.maps.GeocoderStatus.OK) {
if (res.length > 1) {
console.log(`Need unique result, but got ${res.length}`);
return "notUnique";
}
var loc = res[0].geometry.location;
this.resto.lat = loc.lat();
this.resto.lng = loc.lng();
this.zoom = 16;
this.$scope.$apply();
return "good";
} else {
console.log(" not found - try again?");
return "notFound";
}
});
});

Related

Widget toggle functionality with $compile

I need to implement toggle functionality for the widget. When the user clicks on the minimization button then widget should shrink and expand when click on maximize button respectively.
I'm trying to achieve this functionality with below piece of code.
Functionality working as expected but it is registering the event multiple times(I'm emitting the event and catching in the filterTemplate directive).
How can we stop registering the event multiple times ?
Or
Is there anyway to like compiling once and on toggle button bind the template/directive to DOM and to make it work rest of the functionality .
So could you please help me to fix this.
function bindFilterTemplate(minimize) {
if ($scope.item && !minimize) {
if ($scope.item.filterTemplate) { // filter template is custom
// directive like this
// "<widget></widget>"
$timeout(function () {
var filterElement = angular.element($scope.item.filterTemplate);
var filterBody = element.find('.cls-filter-body');
filterElement.appendTo(filterBody);
$compile(filterElement)($scope); // Compiling with
// current scope on every time when user click on
// the minimization button.
});
}
} else {
$timeout(function () {
element.find('.cls-filter-body').empty();
});
}
}
bindFilterTemplate();
// Directive
app.directive('widget', function () {
return {
restrict: 'E',
controller: 'widgetController',
link: function ($scope, elem) {
// Some code
}
};
});
// Controller
app.controller('widgetController', function ($scope) {
// This event emitting from parent directive
// On every compile, the event is registering with scope.
// So it is triggering multiple times.
$scope.$on('evt.filer', function ($evt) {
// Server call
});
});
I fixed this issue by creating new scope with $scope.$new().
When user minimizes the widget destroying the scope.
Please let me know if you have any other solution to fix this.
function bindFilterTemplate(minimize) {
// Creating the new scope.
$scope.newChildScope = $scope.$new();
if ($scope.item && !minimize) {
if ($scope.item.filterTemplate) {
$timeout(function () {
var filterElement = angular.element($scope.item.filterTemplate);
var filterBody = element.find('.cls-filter-body');
filterElement.appendTo(filterBody);
$compile(filterElement)($scope.newChildScope);
});
}
} else {
$timeout(function () {
if ($scope.newChildScope) {
// Destroying the new scope
$scope.newChildScope.$destroy();
}
element.find('.cls-filter-body').empty();
});
}
}

AngularJS - huge directive

I have a website that has to display different set of data on a map. The map will always be the same - Some areas with 'onhover' effect and tooltip.
There is about 10 different sets of data.
I created a directive to display the map
Directive (only draw the map)
angular.module('PluvioradApp.controllers')
.directive('map', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
var svg = d3.select(element[0])
.append("div")
.classed("svg-container", true) //container class to make it responsive
.append("svg")
//responsive SVG needs these 2 attributes and no width and height attr
.attr("preserveAspectRatio", "xMinYMin meet")
.attr("viewBox", "0 0 1000 500")
//class to make it responsive
.classed("svg-content-responsive", true);
var g = svg.append("g");
//Scale / translate / ...
var lineFunction = d3.svg.line()
.x(function(d) { return (d[0]+50000)/500; })
.y(function(d) { return (-d[1]+170000)/500; })
.interpolate("linear");
//Draw map
var path = g.selectAll('path')
.data(data.areas)
.enter().append("path")
.attr("d", function(d){ return lineFunction(d.borders)})
.attr("fill", "#D5708B")
.on('mouseover', function(d) {
d3.select(this).style('fill', 'orange');
d3.select(this).text(function(d){return "yeah";})
})
.on('mouseout', function(d) {
g.selectAll('path').style('fill', '#D5708B');
});
// zoom and pan
var zoom = d3.behavior.zoom()
.on("zoom", function() {
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
g.selectAll("path")
.attr("d", function(d){ return lineFunction(d.borders)});
});
svg.call(zoom);
}
}
});
My idea was to get the data to display from the controller (it comes from an API) and send it to the directive. Inside the above directive I will add a big switch or multiple if to display the correct data with the correct colors, size,...
I am sure that there is another way to split the work.
For example :
1st directive to display the map. It can be reuse multiple time
2nd directive to display set 1
3rd directive to display set 2
If this is the correct way, how can I achieve this ?
Additional information
I have a menu with a dropdown to select which data will be displayed. For the moment, the items redirect to a page containing the map directive above
Have a folder where you will have a bunch of service, where each service will be one of your data set.
Set1Service, Set2Service. etc.
Each of this will have own logic.
Have a factory service which will return one of your service.
for example:
(new FactoryService())->get('dataSetItem'); //this will return one of services from point 1.
Inject FactoryService in you directive use it.
In factory you will have the logic how to parse your data set, to determine what DataSetService you will have to return
This is extensible an easy to use.
All that I described are more related to Strategy and Factory pattern, you can read more about those and this will help you to have more abstract implementation.
angular.module('PluvioradApp.controllers')
.directive('map', function(factoryService) {
return {
restrict: 'E',
scope: {
dataSet: '='
}
link: function(scope, element, attrs) {
//all your code
var dataSetService = factoryService.get(scope.dataset);
var result = dataSetService.seed(d3);
}
}).service('factoryService', function() {
this.get = function(name) {
var service = null;
switch (name) {
case 'set1'
service = new DataSet1();
break;
case 'set2'
service = new DataSet2();
break;
}
return service;
}
});
function DataSet1() {
}
DataSet1.prototype.seed = function(d3) {
//d3 logic you have access here;
}
function DataSet2() {
}
DataSet2.prototype.seed = function(d3) {
//d3 logic you have access here;
}

calling a function when AngularUI Bootstrap modal has been dismissed and animation has finished executing

I'm using the Angular UI bootstrap modal and I ran into a bit of a problem.
I want to call a function when the bootstrap modal dismiss animation is finished. The code block below will call the cancel() function as soon as the modal starts to be dismissed - and NOT when the modal dismiss animation has finished.
Angular UI does not use events, so there is no 'hidden.bs.modal' event being fired (at least, not to my knowledge).
var instance = $modal.open({...});
instance.result.then(function(data) {
return success(data);
}, function() {
return cancel();
})
The cancel() block immediately runs when the modal starts to close. I need code to execute when the closing animation for the Bootstrap modal finishes.
How can I achieve this with angular UI?
Component for reference:
https://angular-ui.github.io/bootstrap/#/modal
Thanks!
A little late but hope it still helps! You can hijack the uib-modal-window directive and check when its scope gets destroyed (it is an isolated scope directive). The scope is destroyed when the modal is finally removed from the document. I would also use a service to encapsulate the functionality:
Service
app.service('Modals', function ($uibModal, $q) {
var service = this,
// Unique class prefix
WINDOW_CLASS_PREFIX = 'modal-window-interceptor-',
// Map to save created modal instances (key is unique class)
openedWindows = {};
this.open = function (options) {
// create unique class
var windowClass = _.uniqueId(WINDOW_CLASS_PREFIX);
// check if we already have a defined class
if (options.windowClass) {
options.windowClass += ' ' + windowClass;
} else {
options.windowClass = windowClass;
}
// create new modal instance
var instance = $uibModal.open(options);
// attach a new promise which will be resolved when the modal is removed
var removedDeferred = $q.defer();
instance.removed = removedDeferred.promise;
// remember instance in internal map
openedWindows[windowClass] = {
instance: instance,
removedDeferred: removedDeferred
};
return instance;
};
this.afterRemove = function (modalElement) {
// get the unique window class assigned to the modal
var windowClass = _.find(_.keys(openedWindows), function (windowClass) {
return modalElement.hasClass(windowClass);
});
// check if we have found a valid class
if (!windowClass || !openedWindows[windowClass]) {
return;
}
// get the deferred object, resolve and clean up
var removedDeferred = openedWindows[windowClass].removedDeferred;
removedDeferred.resolve();
delete openedWindows[windowClass];
};
return this;
});
Directive
app.directive('uibModalWindow', function (Modals) {
return {
link: function (scope, element) {
scope.$on('$destroy', function () {
Modals.afterRemove(element);
});
}
}
});
And use it in your controller as follows:
app.controller('MainCtrl', function ($scope, Modals) {
$scope.openModal = function () {
var instance = Modals.open({
template: '<div class="modal-body">Close Me</div>' +
'<div class="modal-footer"><a class="btn btn-default" ng-click="$close()">Close</a></div>'
});
instance.result.finally(function () {
alert('result');
});
instance.removed.then(function () {
alert('closed');
});
};
});
I also wrote a blog post about it here.

Dynamically added element's directive doesn't work

I'm trying to build a simple infinite scroll. It loads the data fine but after loading, new added elements' directives don't work.
This is relevant part of the scroll checking and data loading directive.
.directive("scrollCheck", function ($window, $http) {
return function(scope, element, attrs) {
angular.element($window).bind("scroll", function() {
// calculating windowBottom and docHeight here then
if (windowBottom >= (docHeight - 100)) {
// doing some work here then
$http.get('service page').then(function (result) {
if (result.data.trim() != "") {
var newDiv = angular.element(result.data);
element.append(newDiv);
}
// doing some other work
},function () {
// error handling here
});
}
scope.$apply();
});
};
})
Service page returns some repeats of this structure as result.data
<div ...>
<div ... ng-click="test($event)"></div>
<div ...>...</div>
</div>
As i said data loads just fine but those test() functions in ng-clickdirectives don't work. How to get em work?
I believe you are going to need to compile the html element returned. Something like this
$compile(newDiv)(scope); // Corrected. Thanks
You'll need to be sure and pass in $compile into your function

AngularJS directive: Updating the isolated scope

I want to create a directive which displays changing data. For simplicity let's say I want to display the current time. This means that once a second the directive needs to refresh itself.
In the docs there is an example for just this case (plunkr), but it procedurally updates the directive's content. I wonder if it could be done using data binding as well.
I imagine something like this:
module.directive('dateTime', function($interval) {
return {
scope: { // start with an empty isolated scope
},
template: '{{currentTime}}', // display time fetched from isolated scope
init: function(isolatedScope) {
$interval(function() {
isolatedScope.currentTime = new Date(); /* update isolated scope */
}, 1000);
},
destroy: function() { /* stop interval */ }
};
}
Is something like that possible? How?
Sure it's possible. The init() function you use in your code must be named link, and the destroy() function must be replaced by a listener on the $destroy event on the element passed to the link function:
module.directive('dateTime', function($interval) {
return {
scope: {
},
template: '{{currentTime}}',
link: function(isolatedScope, element) {
var interval = $interval(function() {
isolatedScope.currentTime = new Date(); /* update isolated scope */
}, 1000);
element.on('$destroy', function() {
$interval.cancel(interval);
});
}
};
}
Working example: http://plnkr.co/edit/rjwYZmR4qJ9Jn28d3jXR?p=preview

Resources