Z
Z
Zakharov Alexander2015-10-10 01:18:02
JavaScript
Zakharov Alexander, 2015-10-10 01:18:02

Any fans/lovers of Angular? I propose to discuss one find.?

Hello.
update. 2015.10.10 02:31.
It seems to me that this find is very similar to xslt styles for JSON.
Introductory (Find at the end)
Got one problem here. There is a project in which, among other components, Angular is actively used. I won't bore you with the details of the project. There is a fairly large list of objects represented by an array of the same type of data, for example, one of the objects looks like this (nothing special):

var arr = [
 {
    position : 66,
    center : [59.7235, 28.4731],
    name : 	"Автомобильная дорога к Карбамидному заводу",
    projectref: "projects/263/?clear_cache=Y",
    pictureprojectref : "images/objects/Карбамидный_завод.300x180.jpg",
    popupText: "текст1 [name] ещё текст [projectref] ещё немного текста [name]. А теперь гляньте сюда: [projectref], классная картинка [pictureprojectref]",
 }
]
:
Notice the popupText property . It's not just a string - it's a prototype of the result. From it you need to get an inscription that will be displayed on the screen. And in square brackets, respectively, it is necessary to substitute the values ​​of the fields of the object itself. On the one hand, one could not think too long and put this property into some external loop, for example:
var arr=[...];
for(var i=0; i<=arr.length-1; i++{
    var arr_i = arr[i];
    arr_i.popupText = "текст1 "+arr_i.name+" ещё текст "+projectref+" ещё немного текста "+name+". А теперь гляньте сюда: "+projectref+", классная картинка "+pictureprojectref+"";
}

But the problem crept up from where they did not expect. In another object, the popupText string is already different:
var arr = [
{
    position : 66,
    center : [59.7235, 28.4731],
    name : 	"Автомобильная дорога к Карбамидному заводу",
    projectref: "projects/263/?clear_cache=Y",
    pictureprojectref : "images/objects/Карбамидный_завод.300x180.jpg",
    popupText : "текст1 [name] ещё текст [projectref] ещё немного текста [name]. А теперь гляньте сюда: [projectref], классная картинка [pictureprojectref]",
},
{
    position : 67,
    center : [59.8113, 30.0687],
    name : 	"Концепция транспортного обеспечения территории п. Новоселье, входящего в состав Муниципального образования «Аннинское сельское поселение» Ломоносовского муниципального района Ленинградской области",
    projectref: "projects/226/?clear_cache=Y",
    pictureprojectref : "images/objects/Новоселье.300x142.jpg",
    popupText : "классная картинка [pictureprojectref], находится в описании [projectref]. А название вот такое: [name] ",
}];

And now it will not work to loop through all objects . Is it legal to use replace here? Maybe yes, maybe not. Firstly, you can’t trust replacements so that they don’t contain the same record with the field name (it doesn’t matter if it’s accidental or malicious intent), and secondly, I really wanted to find something more interesting. Angular has a $compile service , which means that instead of the square brackets that I used in the examples, you can use Angular ones:
Find in the loop
bc579e3fe98d47d596d8dbfe057ed96d.png
<!-- сюда будут выводиться popup тексты: -->
<div id="para"></div>

var arr = [
{
    position : 66,
    center : [59.7235, 28.4731],
    name : 	"Автомобильная дорога к Карбамидному заводу",
    projectref: "projects/263/?clear_cache=Y",
    pictureprojectref : "images/objects/Карбамидный_завод.300x180.jpg",
    popupText : "текст1 {{name}} ещё текст <a href=\"{{projectref}}\">{{name}}</a> ещё немного текста {{name}}. А теперь гляньте сюда: {{projectref}}, классная картинка {{pictureprojectref}}",
},
{
    position : 67,
    center : [59.8113, 30.0687],
    name : 	"Концепция транспортного обеспечения территории п. Новоселье, входящего в состав Муниципального образования «Аннинское сельское поселение» Ломоносовского муниципального района Ленинградской области",
    projectref: "projects/226/?clear_cache=Y",
    pictureprojectref : "images/objects/Новоселье.300x142.jpg",
    popupText : "классная картинка {{pictureprojectref}}, находится в описании {{projectref}}. А название вот такое: {{name}} ",
}];

// Вот теперь и один цикл:
for(var i=0; i<=arr.length-1; i++){
    var scope_i = $scope.$new(true);
    var arr_i = arr[i];
    angular.extend(scope_i, arr_i);
    // Находка:
    var temp = $compile(arr_i.popupText)(scope_i);  // angular компилирует строку popupText, подставляя туда данные из объекта
    angular.element("#para").append(temp);  // вывести на экран.
}

As a result, all popupText in the desired form will fall into #para. This application of $compile seems like a godsend to me , although the situation from the outside may look like this:
42a0d57cdc304863b2b9e06901319c9f.png
Maybe there are other options for how to make these replacements differently, in addition to the aforementioned JS replace and angular? (suddenly you have something simpler to offer)
PS Thank you for reading :)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aves, 2015-10-10
@Aves

So why is replace worse in the end?

arr.map(e => e.popupText.replace(/\[(.+?)\]/g, (s, p) => p in e ? e[p] : s))

L
lega, 2015-10-10
@lega

Why not, for good, the popup plugin itself should do this.
In this case, you can get profit using filters. And in the case of Angular Light, you can use asynchronous filters (or text directives) and then it will be possible for the template itself to get the text from the links from the server, for example "{{companyId | loadCompanyNameById}}". An example in Angular Light, with an asynchronous filter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question