hszeto hszeto - 3 months ago 8
AngularJS Question

Angular app with jquery-confirm. How to interpolate the select in the modal?

I am working on an Angular page. When user clicks on a link, a modal pops up using jquery-confirm. In the modal, there will be a select dropdown.

The length of options will depend on the particular user. If the user has many groups, the dropdown will be longer.

getAllGroups makes an HTTP GET request and returns an object called res with an array of group objects.

group_names is an array of group names

I have problems interpolating this array in to $.confirm

getGroups_request = AppService.getAllGroups( token )
getGroups_request.promise.then (res) ->
group_names = res.data.map (m) ->
title: 'Select a group'
content: '<select id="target"></select><script>$.each(['+group_names+'], function(index, data){$("#target").append("<option>"+data+"</option>");});</script>'

Let's say, group_names=["aaa","bbb","ccc"]

When I run this, the chrome console would say

ReferenceError: aaa is not defined

However, if I hard code the array in $.each like this

content: '<select id="target"></select><script>$.each(["aaa","bbb","ccc"], function(index, data){$("#target").append("<option>"+data+"</option>");});</script>'

It works.

What is the proper syntax for this kind of interpolation?


It looks to me that where you use group_names within the script to be executed, group_names does not get stringified with the quotes that are necessary to produce a valid JavaScript array of strings. This means that [aaa,bbb,ccc] is produced where ["aaa","bbb","ccc"] is required. You would need to fix that by adding the commas:

'["' + group_names.join('","') + '"]'

However, I don't think that this is an attractive solution. Writing a string of JavaScript to be executed seems odd when you are already within an executing JavaScript context. Why not do the string building before you call $.confirm:

$select = $('<select />', { id: 'target' })
    .append group_names.map (group_name) ->
        $('<option />')
            .text group_name
            .get 0

    title: 'Select a group',
    content: $select[0].outerHTML

Note: Please forgive my CoffeeScript. I don't normally code in this language, but I thought it might be nice to keep consistent with the code in the question.