I would like to to a "map" tag witch should contains "marker" tags.
my problem is that I would like to set the "marker" attributes using variables from the "map" parent scope.
if I do this:
<map center="{{userPosition}}">
<marker lat="13.555232324" lng="43.555232324" text="Text1" on-click="callback('id_0')" ></marker>
</map>
my code works, but I would like to do something like:
<map center="{{userPosition}}">
<marker lat="{{nearRooms['id_0'].lat}}" lng="{{nearRooms['id_0'].lng}}" text="Text1" on-click="callback('id_0')" ></marker>
</map>
right now I can just read "lat" as a string.
my map directive:
ngBMap.directive('map', [ function ($compile){
return {
restrict: 'E',
controller: ['$scope', function($scope) {
this.markers = [];
$scope.markers = [];
this.mapHtmlEl = null
this.map = null;
this.exeFunc = function(func, context, args){
$scope.$parent[func].apply(context, args)
}
this.initializeMarkers = function(){
for (var i=0; i<this.markers.length; i++) {
var marker = this.markers[i];
this.map.entities.push(marker);
}
}
this.initializeMap = function(scope, elem, attrs){
var map_canvas = document.createElement('div')
var _thisCtrl = this;
....
this.mapHtmlEl = map_canvas;
}
this.setCenter = function(position){
var position = eval(position)
var _position = new Microsoft.Maps.Location(position[0], position[1])
if(this.map)
this.map.setView({center : _position});
}
}],
scope: {
'center': '#',
},
link: function(scope, element, attrs, ctrl) {
scope.$watch('center', function(center) {
console.log('center: '+center)
if(center){
ctrl.setCenter(center)
}
}, false);
ctrl.initializeMap(scope, element, attrs)
element.html(ctrl.mapHtmlEl)
}
}
}]);
my marker directive:
ngBMap.directive('marker', [ function ($compile){
return {
restrict: 'E',
require: '^map',
link: function(scope, element, attrs, mapController) {
console.log('marker init')
var getMarker = function() {
var lat = attrs.lat
.....
var marker = _marker;
return marker;
}//end getMarker
var marker = getMarker();
mapController.markers.push(marker);
}
}}]);
Assuming you are using an Angular version that supports controllerAs, you can do this:
ngBMap.directive('marker', [ function ($compile){
return {
restrict: 'E',
require: '^map',
controllerAs: 'marker',
link: function(scope, element, attrs, mapController) {
var lat = attrs.lat
<map center="{{userPosition}}">
<marker lat="{{marker.nearRooms['id_0'].lat}}" lng="{{marker.nearRooms['id_0'].lng}}" text="Text1" on-click="marker.callback('id_0')" ></marker>
</map>
For it to work in Angular 1.0.x you need to use scope:true to create a child scope that inherits from the parent directive so they don't conflict with each other.
Related
I am using Angularjs 1.6, I made this transclusion type of thing.
var app = angular.module('plunker', []);
app.controller("mainCtrl", function ($scope) {
$scope.testmodel1 = {
testmodel1prop: "testmodel1prop"
};
$scope.testmodel2 = {
testmodel2prop: "testmodel2prop"
}
})
app.directive('tabs', function ($compile) {
return {
restrict: 'E',
scope: {},
transclude: true ,
link: function (scope, el, attrs, ctrl, transcludeFn) {
// transcluded content's scope should inherit from parent
transcludeFn(scope.$parent, function (clonedTranscludedContent) {
var tabs = [];
for (var i = 1; i < clonedTranscludedContent.length; i = i + 2) {
tabs.push(clonedTranscludedContent[i]);
}
for (var i = 0; i < tabs.length; i++) {
debugger;
var jqueryTab = $(clonedTranscludedContent[1]);
var stringTab = jqueryTab.prop('outerHTML');
var model = jqueryTab.attr('model');
var pocoModelFromParent = scope.$parent[model];
var newScope = angular.merge(scope.$parent.$new(), pocoModelFromParent)
var linkFn = $compile(stringTab);
var compiledContent = linkFn(newScope);
el.append(compiledContent);
}
});
}
};
});
app.directive('test', function () {
return {
restrict: 'E',
scope: {},
link: function ($scope, $element, attr) {
$scope.var1 = "test";
},
template: '<p>{{ var1 }}</p>'
};
});
<div ng-app="plunker" >
<div ng-controller="mainCtrl">
<tabs>
<tab model="testmodel1" title="tab2">{{ testmodel1prop }}</tab>
<tab model="testmodel2" title="tab1"> {{ testmodel2prop }} </tab>
</tabs>
</div>
</div>
I would like to get some feedback if this is okay or not.
It works perfectly by the way.
The first thing that pops into my mind is why does 'clonedTranscludedContent' has a sort of empty object at position 1 3 5 7 and so on.I have yet to figure out what that is, probably the ::before in chrome?
I am planning to use this on production actually.
I created this number format directive, but if I use it on more than one input, it doesn't work for all of them, but with only one it works.
Any ideas?
directive('formatUsNumber', function() {
return {
restrict: 'A',
require: 'ngModel',
priority: 100,
link: function(scope, element, attrs, ngModel) {
scope.formatNumber = function() {
var n = element.val();
var dest = n;
if (n.length >= 10) {
if (/^[A-Za-z\s]+$/.test(n)) {
return;
}
dest = n.replace(/\D/g, '');
if (!isNaN(dest)) {
n = dest;
}
if (n.substr(0, 1) != "1") {
n = "1" + n;
}
}
element.val(n);
ngModel.$setViewValue(n);
};
},
};
});
The template:
<input type="text" ng-change="formatNumber()" format-us-number ng-model="myModel" />
Fiddle: http://jsfiddle.net/Lvc0u55v/7479/
I think it's because scope of directive is not isolated.
And also I've made few changes, hope it workes the same
directive('formatUsNumber', function() {
return {
restrict: 'A',
require: 'ngModel',
priority: 100,
scope: true,
link: function(scope, element, attrs, ngModel) {
scope.formatNumber = function() {
var n = ngModel.$modelValue;
if (n.length >= 10) {
if (/^[A-Za-z\s]+$/.test(n)) {
return;
}
n = n.replace(/\D/g, '');
if (!isNaN(dest)) {
n = dest;
}
if (n.substr(0, 1) != "1") {
n = "1" + n;
}
ngModel.$setViewValue(n, 'change:directive');
}
};
},
};
});
U can test it here
Try adding an isolated scope, something like this:
restrict: 'A',
require: 'ngModel',
priority: 100,
scope:{
ngModel:'='
},...
For this use case I think that fits better implements a custom filter instead a directive.
Building Custom AngularJS Filters
Other alternative could be incude a custom parser and/or formatter.
AngularJS - Formatters and Parsers
I have created custom-directive, I want to use it with 'tags-input'. But When I select any value from auto-complete result, It does not select. I don't know why it not working, Please find
Demo Plunker
Index.html
<my-directive apipoint="customerApi" modeldisplay="customer.selected"
ng-model="customer.selected" searchresults="customeruserprofile" change="customerChanged"></my-directive>
Directive:
app.directive("myDirective", ['$http',function($http){
return {
restrict: "E",
templateUrl: 'auto-complete.html',
require: 'ngModel',
scope : {
modeldisplay: "=",
apipoint: "=",
change: "="
},
link : function(scope, element, attrs, ctrl){
scope.loadTags = function(query) {
return $http.get(scope.apipoint[0]);
};
scope.addCustomerTag = function($tag){
var selectedCustomer = scope.modeldisplay;
if(selectedCustomer === undefined){
return true;
}
return false;
};
scope.tagAdded = function($tag){
scope.selectedmodel = $tag
var selectFun=scope.change;
selectFun();
};
scope.removedCustomerTag = function(){
scope.modeldisplay = undefined;
scope.selectedmodel = undefined;
};
scope.tagAdded = function($tag){
scope.selectedmodel = $tag;
scope.tagid = $tag.customer_id;
scope.change();
};
}
};
}]);
I created a fiddle that simulate my issue. I'm using ng-repeat to create some nodes. But these nodes are to be used by another library (Openlayers) which "move" (appendChild) these nodes to another place in the DOM.
So, a fight for these nodes is happening. Is there a way to tell ngRepeat to stop re-sorting, re-creating (not sure about the best term)?
http://jsfiddle.net/jonataswalker/dbxmbxu9/
Markup
<button ng-click="create()">New Record</button>
<div data-label="Created here">
<div
id="hint-{{$index}}"
class="hint--always hint--right"
data-hint="{{row.desc}}"
ng-repeat="row in rows track by row.id"
on-render>{{row.desc}}
</div>
</div>
<div id="wrap" data-label="I'd like all to be here"></div>
JS
app.controller('ctrl', ['$scope', function($scope) {
$scope.rows = [];
$scope.count = 0;
var wrap = document.getElementById('wrap');
$scope.create = function(){
var c = $scope.count++;
$scope.rows.push({
id: c,
desc: 'dummy-desc-' + c
});
};
$scope.move = function(div){
wrap.appendChild(div);
};
}]);
app.directive('onRender', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function(){
scope.move(element[0]);
});
}
}
};
}]);
At the end, I had to give up using ng-repeat. Thanks for all comments.
The solution I found is to use $compile service and let the DOM manipulation freely.
http://jsfiddle.net/jonataswalker/y4j679jp/
app.controller('ctrl', ['$scope', function($scope) {
$scope.rows = [];
$scope.count = 0;
var wrap = document.getElementById('wrap');
$scope.move = function(div){
wrap.appendChild(div);
};
}]);
app.directive('button', ['$compile', function($compile){
return {
restrict: 'A',
link: function(scope){
var div = document.getElementById('c1');
scope.create = function(){
var c = scope.count++;
var row = { id: 'hint-' + c, desc: 'any desc #' + c };
var index = scope.rows.push(row) - 1;
var html = [
'<div id="'+row.id+'"',
'class="hint--always hint--right"',
'data-hint="{{rows['+index+'].desc}}"',
'data-index="'+index+'"',
'on-render>{{rows['+index+'].desc}}</div>'
].join(' ');
angular.element(div).append($compile(html)(scope));
};
}
};
}]);
app.directive('onRender', ['$timeout', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
$timeout(function(){
scope.move(element[0]);
}, 2000).then(function(){
$timeout(function(){
scope.rows[attr.index].desc = 'changed .... ' + attr.index;
}, 2000);
});
}
};
}]);
I'm learning AngularJs now, and trying to write my first directives.
So i have a question: is there any way to pass complex options to directive. For example i want to write directive wrapper for slick grid. It has a lot of options, columns for example, and it's imposible to configure it using attributes. Can i do simething like this?
<s-grid>
<s-grid-columns>
<s-grid-column id="title" title="Title"/>
<s-grid-column id="duration" title="Duration"/>
</s-grid-columns>
...
</s-grid>
And get all this properties as json object in s-grid directive?
So i could do it. Is it here any mistakes?
module
.directive('sGrid', [function () {
return {
restrict: 'E',
controller: function($scope) {
$scope.columns = [];
this.setColumns = function(columns) {
$scope.columns = columns;
};
},
link: function (scope, element, attrs, controller, transclude) {
// for clearer present I initialize data right in directive
// start init data
var columns = scope.columns;
var options = {
enableCellNavigation: true,
enableColumnReorder: true
};
var data = [];
for (var i = 0; i < 50000; i++) {
var d = (data[i] = {});
d["id"] = "id_" + i;
d["num"] = i;
d["title"] = "Task " + i;
d["duration"] = "5 days";
d["percentComplete"] = Math.round(Math.random() * 100);
d["start"] = "01/01/2009";
d["finish"] = "01/05/2009";
d["effortDriven"] = (i % 5 == 0);
}
// end init data
// finally render layout
scope.grid = new Slick.Grid(element, data, columns, options);
$(window).resize(function () {
scope.grid.resizeCanvas();
})
}
}
}])
.directive("sGridColumns", function(){
return {
require: '^sGrid',
restrict: 'E',
controller: function($scope) {
var columns = $scope.columns = [];
this.addColumn = function(pane) {
columns.push(pane);
};
},
link: function (scope, element, attrs, gridCtrl){
gridCtrl.setColumns(scope.columns);
}
}
})
.directive('sGridColumn', function() {
return {
require: '^sGridColumns',
restrict: 'E',
transclude: 'element',
link: function (scope, element, attrs, gridCtrl) {
scope.field = scope.field || scope.id;
scope.title = scope.title || scope.field;
gridCtrl.addColumn({
id: attrs.id,
field: attrs.field || attrs.id,
name: attrs.name || attrs.field || attrs.id
});
}
};
});
And declaration:
<s-grid>
<s-grid-columns>
<s-grid-column id="title" name="Title"></s-grid-column>
<s-grid-column id="duration" name="Duration"></s-grid-column>
</s-grid-columns>
</s-grid>