How to $compile an AngularJS template using a newly created scope? - angularjs

I am creating a pop-up modal that I want to have the capabilities of being updated dynamically using a newly created $scope. I want to do something like this:
var myNewScope = $scope.$new();
myNewScope.name = 'Jack';
ModalService.open('Hello, {{ name }}', myNewScope);
Then in my ModalService.open method I want to compile that string with the given scope like this
// ... other service stuff
service.open = function(template, scope){
var compiledText = $compile(template)(scope);
// I want compiledText = 'Hello, Jack'
}

Welp... I don't think angular has a built in way to do this.. so I just built my own version.
app.controller('TestController', function($scope, $compile){
var scope = $scope.$new();
scope.percentage = {Value:55};
scope.name = 'Jack';
var msg = 'We are at {{ percentage.Value }}% done, {{ name }}.. {{ 4/3 }}';
var element = msg.replace(/{{\s*([a-zA-Z0-9+-/*//\s.]*)\s*}}/g, function($0, $1){
return scope.$eval($1);
} );
console.log(element); // prints 'We are at 55% done, Jack.. 1.3333333333333333'
});
This seems to be working pretty well

Related

Updating HTML in Angular is not working

I am still learning angular and in my example projekt I have a problem on updating the view.
Got this in my header ....
<meta charset="UTF-8">
<title>{{ name }}</title>
And this in my body:
<body ng-controller="BodyController as body">
<input type="button" ng-click="changeTitle()" name="changeNameButton" value="change name"/>
This is my head controller:
myApp.controller('HeadController',
['$scope', 'ApplicationService', 'DataService', 'UserService', function ($scope, ApplicationService, DataService, UserService) {
var self = this;
$scope.name = ApplicationService.getTitle();
}]
);
And here is my body controller:
myApp.controller('BodyController', ['$scope', 'ApplicationService', function ($scope, ApplicationService) {
$scope.text = 'Hello, Angular fanatic.';
$scope.changeTitle = function () {
console.log('change the title');
ApplicationService.setTitle('test');
}
}]);
This is my application service
myApp.service('ApplicationService', ['ConfigurationService', function(ConfigurationService){
this.title = '';
this.setTitle = function (newTitle) {
console.log('new title (setter): ' + this.title);
this.title = newTitle
}
this.getTitle = function () {
if(this.title==''){
this.title = ConfigurationService.title + ' | ' + ConfigurationService.subtitle;
}
console.log('new title (getter): ' + this.title);
return this.title;
}
}]);
So far so good and sorry that I do not use codepen, etc. But it was not working in it, ...
My Problem: It is setting the title on initial load of the website, but not on pressing the button. The new name is set to ApplicationService.title, but header controller does not update it. Whats is wrong in this case? How can I update the title in the view...?
Regards
n00n
see the codepen for it: https://codepen.io/n00n/pen/bqaGKY
What you're doing is the equivalent of the following simple code:
//in the header controller
var name = service.getTitle();
// in the header template
display(name);
// later, in the body
service.setTitle('test');
// in the header template
display(name);
You see that this can't work: the variable name in the header controller has been initialized when the controller was created, and assigning a new value to the title stored in the service can't magically change the value of the name variable in the header controller. What you want is to display the title in the service:
<title>{{ getTitle() }}</title>
$scope.getTitle = function() {
return ApplicationService.getTitle();
};
That didn't work because you're calling getTitle method when title wasn't set. So that's it is referring to older title('undefined'). You can change your binding to
$scope.getTitle = ApplicationService.getTitle;
And then change HTML to
{{getTitle()}}
So title will get fetch from service and updated on the page on each digest cycle.
Other thing which I'd like to mention is, don't use(mix) $scope when you are using controllerAs, so then remove $scope from controller and bind data to below
var vm = this;
vm.getTitle = ApplicationService.getTitle;

Why does my scope binding to a service array not update when the array gets replaced

I have a scope binding to an array stored in a service.
When the array changes, the scope notices the change and updates the values in my template.
However, when the Array gets replaced by another array, the scope doesn't seem to recognize a change and won't update the list.
I know that this is a common behaviour of angularjs and that it's probably intended to be like this, but I don't get why.
In my understanding, the scope variable should update, whenever the bound reference changes.
Is $scope.myVar = anyOtherVar; not equivalent to a $scope.$watch('anyOtherVar',function(..){//update myVar}); ?
See my fiddle for demonstrating the problem.
http://jsfiddle.net/sL9k7q9L/1/
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
myApp.factory('myService', function() {
var anyArray = [{"name":"peter"}];
var anyOtherArray = [{"name":"laura"}];
return {
anyArray: anyArray,
newElement: function(){
anyArray.push({"name":"bob"});
},
replaceWholeArray: function(){
anyArray = anyOtherArray;
console.log(anyArray);
}
}
});
function MyCtrl($scope,myService) {
$scope.elements = myService.anyArray;
$scope.newElement = function(){
myService.newElement();
}
$scope.replaceWholeArray = function(){
myService.replaceWholeArray();
}
}
and the corresponding template:
<div ng-controller="MyCtrl">
<button ng-click="newElement()">
newElement()
</button>
<button ng-click="replaceWholeArray()">
replaceWholeArray()
</button>
<ul>
<li ng-repeat="el in elements">{{el.name}}</li>
</ul>
</div>
You are updating variables but that doesn't update any other variable assignments that were made using the original variable.
Thus reference to original array is broken for myService.anyArray
Simple example
var a = 1;
var b = a;
a = 2;
alert(b);// is still 1 due to value of `a` when it was assigned
Instead just update the factory object property but to do that you need to store a reference to the returned object first
myApp.factory('myService', function() {
var anyArray = [...];
var anyOtherArray = [...];
var factoryObject = {
anyArray: anyArray,
newElement: function() {
anyArray.push({"name": "bob"});
},
replaceWholeArray: function() {
// change this part
//anyArray = anyOtherArray;
// To:
factoryObject.anyArray = anyOtherArray;
}
}
return factoryObject
});

ng-hide & ng-show in leaflet legend

I tried to create a leaflet legend using the 'ng-show' and 'ng-hide' attributes.
Unfortunately, the legend is not created on site load but on map load.
The attributes don't seem to work if they are added with javascript directly.
This code:
onAdd: function() {
var controlDiv = L.DomUtil.create('div', 'air-quality-legend');
controlDiv.setAttribute('ng-hide', 'true');
controlDiv.className = "airQualityIndex";
L.DomEvent
.addListener(controlDiv, 'click', L.DomEvent.stopPropagation)
.addListener(controlDiv, 'click', L.DomEvent.preventDefault);
var table = document.createElement('table');
var tr = document.createElement('table');
var td = document.createElement('table');
td.innerHTML = "test";
tr.appendChild(td);
table.appendChild(tr);
controlDiv.appendChild(table);
return controlDiv;
}
Produces that output.
As described there is a table when there should not.
Is there any way to add 'ng-hide' or 'ng-show' via javascript on runtime?
Thank you for your help in advance.
You'll need to compile the DOM of your custom control. To do that, you'll need to inject $compile into your controller, then after having added the control to your map use the getContainer method on your control instance and run $compile on it and attach it to the scope:
Control:
L.Control.Custom = L.Control.extend({
onAdd: function () {
var container = L.DomUtil.create('div', 'leaflet-control-custom')
header = L.DomUtil.create('h1', 'leaflet-control-custom-header', container);
header.textContent = 'NG-Hide test';
header.setAttribute('ng-hide', 'hide');
return container;
}
});
Controller:
angular.module('app').controller('controller', [
'$scope', 'leaflet', '$compile',
function ($scope, leaflet, $compile) {
$scope.hide = false;
leaflet.map.then(function (map) {
var control = new L.Control.Custom().addTo(map);
$compile(control.getContainer())($scope);
});
}
]);
Here's a working example on Plunker: http://plnkr.co/edit/xzRwTp9OZ8Zp8v7ktt2c?p=preview

angularjs directive communication

I am new to angularjs, and I have been reading a ton of documentation and reading through various articles and tutorials as well as videos to help me figure this stuff out.
I am trying to get two directives to interchange information between themselves. a really simplified version of what i am trying to do is at odetocode (http://odetocode.com/blogs/scott/archive/2013/09/11/moving-data-in-an-angularjs-directive.aspx) where k scott allen has wrapped his directives with a div that has the ng-controller attribute it works beautifully.
I have a slightly more complex test I am working on, and I am trying to get it to work similarly to the code I have mentioned.
my two directives talk to each other when I list the ng-controller attribute in the actual template for each directive. it works, but I don't think it is correct. the actual controller code is run twice, once for each directive.
when I move the controller into the div that wraps the two directives, the two directives stop interacting (the change event in the location-selector template doesn't change the park in the controller). I am pretty sure it has something to do with the scope. if anyone can point me in the right direction, or where I should look for information, that would be much appreciated.
here is my fiddle showing my code http://jsfiddle.net/jgbL9/25/
<div ng-app="myApp">
<location-selector ></location-selector ><br/>
<portal-map ></portal-map >
</div>
var App = angular.module('myApp', ['ngResource']);
App.directive('locationSelector',['parkList', function(parkList) {
return {
restrict: 'E',
scope: {
parkId : '=',
parkName : '='
},
template: '<select ng-controller="portalMapCtrl"'+
' ng-model="listParks" ng-change="changePark()" '+
' park-id="parkId" park-name="parkName" ' +
' ng-options="park as park.attributes.NAME for park in Parks" >'+
'</select>',
link: function (scope,element,attrs){
parkList.getListFromGIS().success(function(data) {
scope.Parks = data.features;
});
}
};
}]);
App.directive('portalMap', function(){
return {
restrict: 'E',
scope:{
parkId: "=",
parkName: "="
},
template: '<style type="text/css" media="screen">'+
'#mapCanvas {height: 500px; width:75%; border:thin black solid; }'+
'</style>'+
'<div id="mapCanvas" park-id="parkId" park-name="parkName" ng-controller="portalMapCtrl" ></div>'
}
});
App.controller('portalMapCtrl',['$scope','parkList', function( $scope, parkList ){
var map = {};
var STREETMAPSERVICE = "https://gis.odot.state.or.us/ArcGIS/rest/services/BASEMAPS/Basemap_Streets/MapServer";
var FOTOSSERVICE = "https://maps.prd.state.or.us/arcgis/rest/services/ESRI_TEST/MapServer?f=jsapi";
var UTILSSERVICE = "http://gis.prd.state.or.us/ArcGIS/rest/services/OPRDAssets/MapServer";
var UTILSSERVICE_PARKLAYER = 0;
var UTILSSERVICE_STRUCTUREPOLY = 7;
var UTILSSERVICE_SURFACE = 11;
var UTILSSERVICE_PARCELS = 12;
var timer;
var ALL_LAYERS = [UTILSSERVICE_PARKLAYER,UTILSSERVICE_STRUCTUREPOLY,UTILSSERVICE_SURFACE,UTILSSERVICE_PARCELS];
$scope.parkId = 0;
$scope.parkName = "";
$scope.changePark = function (){
require(["esri/SpatialReference","esri/geometry/Polygon"],
function(SpatialReference,Polygon){
console.log('change park');
$scope.parkId = $scope.listParks.attributes.PARK_HUB_ID;
$scope.parkName = $scope.listParks.attributes.NAME;
parkList.getParkFromGIS($scope.parkId).then(function(data){
var x = data.data;
var y = x.features[0];
var rings = y['geometry'];
var poly = new Polygon(rings);
var xtnt = poly.getExtent();
var sr = new SpatialReference({wkid:2992});
xtnt.setSpatialReference (sr);
map.setExtent(xtnt,true);
});
});
};
function addService(srvc, srvcType, lyrId){require([
"esri/layers/ArcGISTiledMapServiceLayer",
"esri/layers/ArcGISDynamicMapServiceLayer",
"esri/layers/ImageParameters"], function(Tiled,Dynamic,Parameters){
var mapService = {};
if(srvcType == 'Tiled'){
mapService = new Tiled(srvc);
}else{
var imageParameters = new Parameters();
imageParameters.layerIds = lyrId;
imageParameters.transparent = true;
mapService = new Dynamic(srvc,{"imageParameters":imageParameters});
}
map.addLayer(mapService);
});
}
function createMap(){
require(["esri/map"],function(Map){
console.log('create map');
map = new Map("mapCanvas");
addService(STREETMAPSERVICE,'Tiled');
addService(FOTOSSERVICE,'Tiled');
addService(UTILSSERVICE,'Dynamic',ALL_LAYERS);
});
}
createMap();
}]);
App.factory('parkList',['$http', function($http) {
return {
getListFromGIS: function() {
var myUrl = 'http://maps.prd.state.or.us/arcgis/rest/services/ESRI_TEST/MapServer/0/query?where=OBJECTID+%3E+0&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelIntersects&outFields=PARK_HUB_ID%2CNAME&returnGeometry=false&&returnIdsOnly=false&returnCountOnly=false&orderByFields=NAME&returnZ=false&returnM=false&returnDistinctValues=true&f=pjson&callback=JSON_CALLBACK';
return $http ({ url: myUrl, method: 'JSONP'});
},
getParkFromGIS: function (id){
var myUrl = "http://maps.prd.state.or.us/arcgis/rest/services/ESRI_TEST/MapServer/0/query?where=PARK_HUB_ID%3d"+id+"&f=pjson&callback=JSON_CALLBACK";
return $http ({ url: myUrl, method: 'JSONP'});
},
JSON_CALLBACK: function(data) {}
};
}]);
(this is the code working with the ng-controller listed in the template of each directive).
any other comments or suggestions you would like to offer about my code structure or code choices will be appreciated also, as I mentioned, I am learning, and the more I can learn the more fun I will have coding.
I believe you're having problems due to your isolate scopes on your directives (the scope: { } in your link function).
I would suggest inlining the templates into your application, instead of trying to make them directives.
In particular, the locationSelector is going to be hard to make a directive - it's usually easier to have your input elements be a part of the element their controller is on.
If you did want to have them be a directive, I'd suggest passing the listParts value into the changePark function:
<select ... ng-change="changePark(listParks)" ...>

AngularJS - Non-http Service Not Updating Scope Variables

I've just been starting on AngularJS and I'm still trying to understand creating services. From this and this, my understanding is as long as changes to variables are within Angular, there is no need to $watch them. I copied code from here, and modified it to see if I can get my first service to work:
myApp.factory('ListService', function() {
var ListService = {};
var list = ['a', 'b', 'c'];
ListService.addItem = function(item) { list.push(item); }
ListService.size = function() { return list.length; }
ListService.size1 = list.length;
return ListService;
});
function Ctrl1($scope, ListService) {
$scope.message = ListService.size();
$scope.addItem = function(){
ListService.addItem('d');
console.log("size() is " + ListService.size());
console.log("size1 is " + ListService.size1);
}
}
function Ctrl2($scope, ListService) {
$scope.message = ListService.size1;
}
The html is simply:
<div ng-controller="Ctrl1"> Count is: {{ message }}
<input type="button" ng-click="addItem">
</div>
<div ng-controller="Ctrl2"> Count is: {{ message }}
</div>
When clicking the button, the console log shows the correct counts, but "messages" remain the same. The original code is supposed to be contrived and was meant to show that services could be used to share code across controllers.
So my questions is, why isn't this working? I apologize if I missed something very simple. I'm a beginner and I'm still trying to get a hang of things.
Instead
$scope.message = ListService.size();
try
$scope.getCount = function () {
return ListService.size();
};
and then in view:
Count is: {{getCount()}}
It is because your $scope.message is primitive value that contains ListService's size at the moment of controller initialization.
(I'm realy bad in English speaking, so sorry for short answer).

Resources