Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles

jeudi 13 août 2015

If argument is blank do not append to string

I want to write a simple javascript function to append to a string of values given arguments, but only if the arguments have values. Here is an example:

function foo(bar){
  return "hello" + bar;  
}

If I run foo() I will get "helloundefined" I want it to just return "hello" and if i run foo('world') that works right now with "helloworld"

I was thinking I could do something like:

return "hello" + null || bar but i would just get "hellonull"

or

return "hello" + if(bar){bar} is invalid syntax.



via Chebli Mohamed

Blanket.js code is instrumented, but will not display when running with Mocha and chai and AMD RequireJS

I've google and SO'd extensively for the answer, and have a found a number of repositories and tutorials with something that wasn't quite what I was looking for, but I attempted to adapt anyway.

According to earlier issues I've looked through, the key to Blanket.js' coverage working is that window._$blanket is defined, and mine is, along with the instrumentations of my source.

However, when my testrunner.html loads, it tends to alternate between a full fledged blanket.js report, or the actual mocha tests (with checkmarks and css and whatnot). I'm inclined to think it has to do with the source being asynchronously loaded with RequireJS.

Here's my testRunner.html:

<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/js/vendor/npm/mocha/mocha.css" />
    <script type="text/javascript" src="js/vendor/mocha/mocha.js"></script>
    <script type="text/javascript" src="js/vendor/require.js"></script>
    <script type="text/javascript" src="/js/test/unit/config.js"></script>
    <script type="text/javascript" src="/js/main.js"></script>
</head>
<body>
<script type="text/javascript" data-cover-only="/js/test/unit/js/some/path/to/"
        src="http://ift.tt/1Wnooca">
</script>
<script type="text/javascript" src="/js/vendor/blanket/src/adapters/mocha-blanket.js"></script>
<script>

    require(['mocha', 'chai', 'chai-jquery', 'sinon'], function(mocha, chai, chaiJquery, sinon) {

        // Init Chai
        chai.should(); //initializes chai.should()
        chai.use(chaiJquery);
        expect = chai.expect;

        mocha.setup({
            ui: 'bdd',
            ignoreLeaks: true
        });

        require([
            '../js/test/unit/js/some/path/to/AModel.test.js',
            '../js/test/unit/js/some/path/to/SModel.test.js',
        ], function(require) {
            mocha.run();
        });
    });
</script>
<div id="mocha"></div>
</body>
</html>

and here's the somemodel.test.js file:

define([
        "app",
        "moment",
        "util/utils",
    ],
    function(app) {

        describe('AModel', function() {

            beforeEach(function () {
                this.AModel = new AModel ({
                    type: undefined,
                    name: undefined, 
                });

                sinon.stub(this.AModel, 'fetch').yieldsTo('success', {
                    fun: "funk"
                });
            });

            afterEach(function () {
                this.AModel = null;
            });




            it('should get a node returned from a given ID', function() {
                var that = this;
                var nodeModel = this.AModel.getNode("node1");
                expect(nodeModel instanceof SModel).to.be.true;
            });

            it('should get the peer nodes of an object', function() {
                var temp = this.AModel.getPeerNodes("node1", "fakeType" );
                expect(temp).to.have.length(10);
            });


        });
    }
);



via Chebli Mohamed

wait for css_parser.getCSSFiles()

I want to render page when CSS will be loaded. Function css_parser.getCSSFiles() reads file asynchronously and sends CSS content to variable css.cssFile . How I can force res.render to wait for end of file reading?

router.get('/main', function(req, res) {

    css_parser.getCSSFiles();
    app.locals.css = css.cssFile;

    res.render('ua', {
        css: app.locals.css,
    });

});

UPDATE: So basically, I want to read also other kind of files. getJSFile is similar to getCSSFiles and I also initialize it before res.render

getJSFile: function(directory, file, variable) {
    fs.readFile(directory + file, 'utf8', function(err, data) {
        if (err) {
            return console.log(err);
        }
        variable.push(data);
});



via Chebli Mohamed

How to pass Javascript date object (formatted datetime) from Laravel API

My Laravel 5 API pulls regular datetime columns from my MySQL db. My JSON datetime output looks like this:

2015-08-13 13:45:00

but the widget reading my JSON expects a JavaScript Date Object? What would be the syntax to pass my datetime as a JavaScript Date Object?

My current Laravel method looks like so:

public function transform($events)
{
    return [
        'startdt' => $events['event_start'],
        'enddt'   => $events['event_end'],
    ];
}

This is the code I have in my widget JS file:

'use strict';

angular
  .module('demo', ['mwl.calendar', 'ui.bootstrap', 'ngTouch', 'ngAnimate'])
  .controller('MainCtrl', function ($modal, moment, $http) {

var vm = this;
vm.calendarView = 'month';
vm.calendarDay = new Date();

$http.get('http://ift.tt/1Wnooc0').success(function(events) {    
    vm.events = events.events;
}); 



via Chebli Mohamed

Handsontable dropdowns with multiple selections

I am trying to extend the handsontable plugin to support multiple selections in its dropdown list. I have already tried extending the base Editor built into the library by modifying the 'dropdownEditor' as suggested http://ift.tt/1IPeF4Y. I spent hours reading and searching through the source for keywords but I am not coming up with anything of real use.

I do not mind if this is answered using the Angular extension or another native ECMA5 or 6 way of extending the http://ift.tt/1FAcz8U plugin.

So far my only thoughts were to actually extend the framework with this bit of code following the patterns that exist. I added all LOC below that are pointing to: multiselect or Handsontable.MultiselectDropdownCell copied the dropdown method, called the new name and everything works, however still cannot see where I could begin to find what I am looking for.

Handsontable.MultiselectDropdownCell ={
  editor: getEditorConstructor('multiselectdropdown'),
  renderer: getRenderer('autocomplete')
};

Handsontable.cellTypes = {
  text: Handsontable.TextCell,
  date: Handsontable.DateCell,
  numeric: Handsontable.NumericCell,
  checkbox: Handsontable.CheckboxCell,
  autocomplete: Handsontable.AutocompleteCell,
  handsontable: Handsontable.HandsontableCell,
  password: Handsontable.PasswordCell,
  dropdown: Handsontable.DropdownCell,
  multiselect: Handsontable.MultiselectDropdownCell
};

Handsontable.cellLookup = { validator: {
    numeric: Handsontable.NumericValidator,
    autocomplete: Handsontable.AutocompleteValidator
}};

I have at a modified version of dropdown editor in place that looks like:

import {getEditor, registerEditor} from './../editors.js';
import {AutocompleteEditor} from './autocompleteEditor.js';

/**
 * @private
 * @editor MultiSelectDropdownEditor
 * @class MultiSelectDropdownEditor
 * @dependencies AutocompleteEditor
 */
class MultiSelectDropdownEditor extends AutocompleteEditor {
  prepare(row, col, prop, td, originalValue, cellProperties) {
    super.prepare(row, col, prop, td, originalValue, cellProperties);
    this.cellProperties.filter = false;
    this.cellProperties.strict = true;
  }
}

export {MultiSelectDropdownEditor};

registerEditor('multiselectdropdown', MultiSelectDropdownEditor);

At this point I have no clue where the click event is happening when the user selects an item from the dropdown list. Debugging has been painful for me because it is through Traceur. I tried setting a click event after the module is ready and the DOM is as well however I cannot get even an alert to fire based off of a click on one of the select dropdown cells. The 'normal' cells I can get a click with a simple:

$('body').on('click','#handsontable td', someAlert)

However not so for the menu contents. Right clicking to inspect the dropdown menu means first disabling the context menu like the one on http://ift.tt/WWRahK. Then you will notice that right clicking to inspect anything will fire an event that closes the dropdown menu you are trying to inspect.

I've put breakpoints all through the libraries source code, I cannot figure this one out.

The only thing I want to do is figure out where the part of the code that highlights the menu item and sets it to an active selection, turn that into a method that accepts multiple selections (up to the entire array of options available, clicking an active item will disable it lets just say).

Then ensuring that those selections are actually in the Handsontable 'data scope'.

Thats it, I don't need it to even render in the cell what things have been chosen, although any help there would be great because unfortunately, I am yet to find the spot when the options in the dropdown are rendered either.

I have also tried using the Select2Editor made for handsontable as seen http://ift.tt/1WnonVE and http://ift.tt/1IPeGWt , however it does not help my cause much. Here is what the dropdown cell in handsontable looks like:

http://ift.tt/1WnoobS

Finally, heres a fiddle: http://ift.tt/1IPeF54

I would be super appreciative if someone could help me out here. Thanks SO!

UPDATE

I have managed to parse the values in the cell and turn the type into an array containing the values (so typing red blue will turn an array containing ['red','blue']) . I have run this array through the internal sort algorithm which parses the options and returns an index of a matching item. I get this working fine and I now am passing the array into the highlight method. This method passes the values the the core library WalkOnTable. I do not see where I can alter the logic to select more than one value instead of unhighlighting the first option.

 this.selectCell = function(row, col, endRow, endCol, scrollToCell, changeListener) {
var coords;
changeListener = typeof changeListener === 'undefined' || changeListener === true;
if (typeof row !== 'number' && !Array.isArray(row) || row < 0 || row >= instance.countRows()) {
  return false;
}
if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) {
  return false;
}
if (typeof endRow !== 'undefined') {
  if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) {
    return false;
  }
  if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) {
    return false;
  }
}
// Normal number value, one item typed in
if (!Array.isArray(row) && typeof row === 'number'){
  coords = new WalkontableCellCoords(row, col);

  walkSelection(coords);
}

This is the spot where I think I need WalkontableCellCoords to be modified to accept an array and then highlight and select both values when the dropdown is opened and closed. I also need to be able to select multiple options via touch or click event.

else {
  // Array found, apply to each value
  new WalkontableCellCoords(row[0], col);
  new WalkontableCellCoords(row[1], col);
}

function walkSelection(coords){
  priv.selRange = new WalkontableCellRange(coords, coords, coords);
  if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) {
    document.activeElement.blur();
  }
  if (changeListener) {
    instance.listen();
  }
  if (typeof endRow === 'undefined') {
    selection.setRangeEnd(priv.selRange.from, scrollToCell);
  } else {
    selection.setRangeEnd(new WalkontableCellCoords(endRow, endCol), scrollToCell);
  }
  instance.selection.finish();
}

return true;

};



via Chebli Mohamed

Nodejs - close socket event reason

Based on the documentation for net module it says that:

Emitted once the socket is fully closed. The argument had_error is a boolean which says if the socket was closed due to a transmission error.

Also, we know that close event will be triggered after error event always:

Emitted when an error occurs. The 'close' event will be called directly following this event.

I have a few doubts regarding how closing of socket works (more precisely when it can happen). I would like to conclude within the script when "close" event is triggered, which side closed the socket. So if "close" event is triggered on client side does this 100% means that socket is closed by other side (and vice versa)? Or I am missing something?

Is it possible for socket to encounter some kind of error which will trigger "close" event even other side is still running? If that is the case how can i conclude from where (and because of what kind of reason) socket is closed? Is it possible to conclude which one of two sides closed the socket (server or client)?



via Chebli Mohamed

Sequelize.js One-to-Many relationship foreign key

I am creating a survey app using Node.js/Express and MySQL with Sequelize.js ORM.

I am having trouble setting the relationship between the 2 models correctly. I'd like to have the Questions' qId foreign key in the Answers Table.

// define the Questions table
var Questions = sequelize.define('Questions', {
  qId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  question: Sequelize.STRING
}, {
  timestamps: false
});

// define the Answers table
var Answers = sequelize.define('Answers', {
  aId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
  answer: Sequelize.STRING,
  answer_count: { type: Sequelize.INTEGER, defaultValue: 0}
}, {
  timestamps: false
});

// define one-to-many relationship
Questions.hasMany(Answers, {as: 'Answers', foreignKey: 'qId'});

Questions.sync({force: true}).then(function() {
  // OPTIONAL: create a new question upon instantiating the db using sequelize
  Questions.create({question: 'what is your language?'});
  Questions.create({question: 'what is your drink?'});
  console.log('created Questions table');
  }).catch(function(error) {
    console.log('error creating Questions table');
  });

Answers.sync({force: true}).then(function() {
  Answers.create({answer: 'python', qId: 1});
  Answers.create({answer: 'javascript', qId: 1});
  Answers.create({answer: 'ruby', qId: 1});
  Answers.create({answer: 'c++', qId: 1});
  Answers.create({answer: 'manhattan', qId: 2});
  Answers.create({answer: 'cosmopolitan', qId: 2});
  console.log('created Answers table');
}).catch(function(error) {
  console.log('error creating Answers table');
});

But when I do MySQL queries:

select * from Questions, Answers where Answers.qId=2;

it's showing the following:

mysql> select * from Answers;
+-----+--------------+--------------+------+
| aId | answer       | answer_count | qId  |
+-----+--------------+--------------+------+
|   1 | python       |            0 |    1 |
|   2 | javascript   |            0 |    1 |
|   3 | ruby         |            0 |    1 |
|   4 | c++          |            0 |    1 |
|   5 | manhattan    |            0 |    2 |
|   6 | cosmopolitan |            0 |    2 |
+-----+--------------+--------------+------+
6 rows in set (0.00 sec)

mysql> select * from Questions;
+-----+------------------------+
| qId | question               |
+-----+------------------------+
|   1 | what is your language? |
|   2 | what is your drink?    |
+-----+------------------------+
2 rows in set (0.00 sec)

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+
|   1 | what is your language? |   5 | manhattan    |            0 |    2 |
|   1 | what is your language? |   6 | cosmopolitan |            0 |    2 |
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

When I'd like it to show

mysql> select * from Questions, Answers where Answers.qId=2;
+-----+------------------------+-----+--------------+--------------+------+
| qId | question               | aId | answer       | answer_count | qId  |
+-----+------------------------+-----+--------------+--------------+------+ 
|   2 | what is your drink?    |   5 | manhattan    |            0 |    2 |
|   2 | what is your drink?    |   6 | cosmopolitan |            0 |    2 |
+-----+------------------------+-----+--------------+--------------+------+

I've been looking at the documentation for a few hours now and any help would be much appreciated :) Thank you.



via Chebli Mohamed

How can I return data from `$http` with a $q resolve?

I have a javascript function which for this question I have simplified. It actually does some things to the data retrieved from the $http call and then I want that data to be made available along with a promise to the function that called it:

getTopics = (queryString: string) => {
        var self = this;
        var defer = self.$q.defer();
        self.$http({
            // cache: true,
            url: self.ac.dataServer + '/api/Topic/GetMapData' + queryString,
            method: "GET"
        })
            .success((data) => {

                var output: ITopics = {
                    details: data
                }
                // output is correctly populated with data
                defer.resolve(output);

                // I also tried this and it get seen in the calling function either
                // defer.resolve('abc');
            })
        return defer.promise;
    };

This calls it:

return topicService.getTopics("/" + subjectService.subject.id)
       .then((data) => {
           // data seems to be not defined
           var x = data;
});

Can someone tell me what I might be doing wrong. I thought the resolve would return data also but it seems not to be doing so.



via Chebli Mohamed

Getting Uncaught TypeError: Cannot read property 'get' of undefined in spite of the conditionals

I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):

var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({


success: function(results) {
    // Do something with the returned Parse.Object values

for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}

    var object = results[i];
     L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
    }
  },
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
});



via Chebli Mohamed

Query Inside Parse Cloud For Loop

I have been trying to run my Parse Cloud Code for some time and can not seem to get around this problem:

I have an array of Parse objectId's called IDArray. I then am sending the array as a parameter of a PFCloud call. Once the array has been sent to the Cloud Code, I can not seem to successfully create a for loop that goes through and updates a number value stored as "points" on Parse for each objectId.

In a nutshell, this is all I am trying to accomplish:

  • I just need to be able to have the for loop go through each objectId and perform an action for each ID.

I have been trying to get this to work for some time but have had no luck. Here is the code that I have been trying to manipulate - hopefully it will give someone a starting point to answer my question.

Parse.Cloud.define('updateAllUsers', function(request, response) {
    var UserData = Parse.Object.extend('UserData');
    var query = new Parse.Query(UserData);
    var list = request.params.listID;
    var currentuser = request.params.user;

                   
    for (var i = 0; i < list.length; i++) {
                   
        var userdata = list[i];
                   
        query.get(list[i], {
                                       
            success: function(userdata) {
                                       
                response.success('Should add up');
                userdata.increment('Done', +1);
                userdata.save();
            },
            error: function() {
                response.error('something went wrong ' );
            }
        });
    }
});

If someone could please help me with this I would be very grateful. Thank you



via Chebli Mohamed

How to obtain only the integer part of a long floating precision number with JS?

I know there's

  • Math.floor
  • parseInt

But about this case:

Math.floor(1.99999999999999999999999999)

returning 2, how could I obtain only its integer part, equals to 1?



via Chebli Mohamed

Javascript generate all numbers between 2 numbers

Well I searched up a lot about this but couldn't find anything with decent documentation on how it works If someone would please explain with an example how to do this that would be great



via Chebli Mohamed

ECMAScript 2015: const in for loops

Which of the two (or neither/ both) code fragments below should be working in a complete ECMAScript 2015 implementation:

for (const e of a)

for (const i = 0; i < a.length; i += 1)

From my understanding, the first example should work because e is initialized for each iteration. Shouldn't this also be the case for i in the second version?

I'm confused because existing implementations (Babel, IE, Firefox, Chrome, ESLint) do not seem to be consistent and have a complete implementation of const, with various behaviours of the two loop variants; I'm also not able to find a concrete point in the standard, so that would be much appreciated.



via Chebli Mohamed

Karma+RequireJS: There is no timestamp, empty test suite. Why do I need to specify this file?

I am having an issue running my unit tests with Karma and its interaction with RequireJS.

I get this error:

'There is no timestamp for /base/bower_components/web/app/services/FooFactoryService.js!' Empty test suite.

As I understand, I must set this to NOT be included, so RequireJS can include it itself manually. My issue is that I have to specify exactly this file to get the tests running again. Wildcards and upper folders do not work, so far as I can see.

Here are my files in karma.conf.js - This one WORKS. As soon as I touch the first pattern, it breaks.

files:
    [
        ...

        {pattern: 'bower_components/**/**/**/FooFactoryService.js', included: false},

        {pattern: 'bower_components/**/*.js', included: false},
        {pattern: 'bower_components/**/*.json', included: false},
        {pattern: 'bower_components/**/*.html', included: false},

        ...
    ],

This works. But if I put a * in place of FooFactoryService.js, or just remove the line entirely and count on 'bower_components/**/*.js', I get the empty test suite error. If I move the line down beneath those three lines, it also fails. It needs to be above them, and it needs to specify the file.

Why does it require me to specify this exact file? Why do wildcards not hit it?



via Chebli Mohamed

Java Script Calculating and Displaying Idle Time

I'm trying to write with javascript and html how to display the time a user is idle (not moving mouse or pressing keys). While the program can detect mousemovements and key presses, the program for some reason isn't calling the idleTime() method which displays the time in minutes and seconds.

I'm wondering why the method isn't getting called, as if it is called it would display true or false if a button is pressed.

var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;

function idleTime() {
  document.write(buttonPressed);
  if (mouseMoved || buttonPressed) {
  startIdle = new Date().getTime();
  }
  document.getElementById('idle').innerHTML =   calculateMin(startIdle) + " minutes: " + calculateSec(startIdle)   + " seconds";
  var t = setTimeout(function() {
  idleTime()
  }, 500);
}

function calculateSec(startIdle1) {
  var currentIdle = new Date().getTime();
  var timeDiff = Math.abs(currentIdle - startIdle1);
  var idleSec = Math.ceil(timeDiff / (1000));
  return idleSec % 60;
}

function calculateMin(startIdle1) {
  var currentIdle = new Date().getTime();
  var timeDiff = Math.abs(currentIdle - startIdle1);
  var idleMin = Math.ceil(timeDiff / (1000 * 60));
  return idleMin;
}

var timer;

// mousemove code
var stoppedElement = document.getElementById("stopped");

function mouseStopped() { // the actual function that is called
   mouseMoved = false;
   stoppedElement.innerHTML = "Mouse stopped";
}

window.addEventListener("mousemove", function() {
   mouseMoved = true;
   stoppedElement.innerHTML = "Mouse moving";
   clearTimeout(timer);
   timer = setTimeout(mouseStopped, 300);
});

//keypress code
var keysElement = document.getElementById('keyPressed');

window.addEventListener("keyup", function() {
   buttonPressed = false;
   keysElement.innerHTML = "Keys not Pressed";
   clearTimeout(timer);
   timer = setTimeout("keysPressed", 300);
});

window.addEventListener("keydown", function() {
   buttonPressed = true;
   keysElement.innerHTML = "Keys Pressed";
   clearTimeout(timer);
   timer = setTimeout("keyPressed", 300);

});

function checkTime(i) {
   if (i < 10) {
      i = "0" + i
   }; // add zero in front of numbers < 10
   return i;
}

Here is the HTML code:

<body onload="idleTime()">


    <div id="stopped"><br>Mouse stopped</br></div>
    <div id="keyPressed"> Keys not Pressed</div>

    <strong>
      <div id="header"><br>Time Idle:</br>
      </div>
    <div id="idle"></div>


    </strong>
  </body>



via Chebli Mohamed

Angular-Slick and dynamic data not initializing correctly

I'm using the angular-slick directive because I have found this to work best for me in most instances. However, I'm still having a problem with getting the slides to initialize properly with dynamic data.

I have a dropdown that updates the relatedResorts json object in a factory. My controller watches for this update and updates scope.relatedResorts accordingly. That all works fine.

Before the slider updates, the slides/content+images are there and it looks like its working. The slick-initialized class has been applied and the excess slides are hidden. But they won't drag or auto advance and the arrows don't even show up.

I then make the images clickable so you can update the json object by clicking on one of the cards as well. The slider actually works better after an image is clicked and the object is refreshed, oddly enough, but the arrows still won't work. You can even drag the slider and see the other slides.

I have tried slick and unslick (which works only after the dom is loaded even with a $timeout applied and seems like a bit of a hack), creating my own directive, and $timeout. I've racked my brains trying to figure this one out.

help please...

HTML:

<slick class="row slider" arrows="true" responsive="breakpoints" slides-to-show=3 slides-to-scroll=1 dots="false" infinite="true" speed="300" touch-move="false" ng-if="relatedResorts.length" init-onload=true data="relatedResorts">
    <div class="card col-md-4 col-sm-6 col-xs-12" ng-repeat="option in relatedResorts" ng-click="resetResort(option.id)">
        <div class="img-container"> 
                <div class="banner">
                <p>{{option.resort_name}}</p>
            </div>
            <img ng-src="assets/images/resorts/{{option.id}}/{{option.resort_img}}" alt="Luxury Resort: {{option.resort_name}}"/>
        </div>
    </div>
</slick>

CONTROLLER:

resortModule.controller('relatedResortsController', ['$scope', 'locaService', '$timeout', function($scope, locaService, $timeout) {
    $scope.relatedResorts;
    $scope.resort;
    $scope.getRelated = function (resort) {
        //Resorts in location/destination on location change
        locaService.fetchRelatedResorts(resort).then(function(result) {
            $scope.relatedResorts= result;
        });
    }
    $scope.resetResort= function(resort){
        //reset resort for app when related resort image is clicked on. 
        $scope.resort= resort;
        locaService.updateResort(resort);
        /*$(".slider").slick('unslick');
        $(".slider").slick();*/
    }

    //watches factory for updates to objects
     $scope.$on('resortUpdated', function() {
        $scope.resort = locaService.resort;
        $scope.getRelated($scope.resort);
    });
}]);



via Chebli Mohamed

How to dynamically append templates to a page in Angular

So the situation is as follows:

I have an input bar where a user can search up a business name or add a person's name (and button to select either choice). Upon hitting enter I want to append a unique instance of a template (with the information entered by the user added). I have 2 templates I've created depending of if the user is searching for a business or a person.

One approach I've thought about is creating an object with the data and adding it with ng-repeat, however I can't seem to get the data loaded, and even then don't know how I can store reference to a template in my collection.

The other idea I've come across is adding a custom directive. But even then I've yet to see an example where someone keeps appending a new instance of a template with different data.

Here is the code so far:

payments.js:

angular.module('payment-App.payments',['ngAutocomplete'])

  .controller('paymentController', function($scope, $templateRequest/*, $cookieStore*/) {

    $scope.businessID;
    $scope.address;
    $scope.isBusiness = false;
    $scope.payees = [];

    $scope.newPayee = function () {
      this.businessID = $scope.businessID;
      this.address = $scope.address;
    }

    $scope.submit = function () {
      var text = document.getElementById("businessID").value.split(",");
      $scope.businessID = text[0];
      $scope.address = text.slice(1).join("");
      $scope.newPayee();
    }

    $scope.addPayee = function () {
      $scope.submit();
      $scope.payees.push(new $scope.newPayee());
      console.log($scope.payees);
    }

    $scope.selectBusiness = function () {
      //turns on autocomplete;
      $scope.isBusiness = true;
    }

    $scope.selectPerson = function () {
      //turns off autocomplete
      $scope.isBusiness = false;
    }

    $scope.fillAddress = function () {
      // body...
    }

})

  .directive("topbar", function(){
  return {
    restrict: "A",
    templateUrl: 'templates/businessTemplate.html',
    replace: true,
    transclude: false,
    scope: {
      businessID: '=topbar'
    }
  }
})

payments.html

<h1>Payments</h1>

<section ng-controller="paymentController">


<div>

  <div class="ui center aligned grid">

    <div class="ui buttons">
      <button class="ui button" ng-click="selectBusiness()">Business</button>
      <button class="ui button arrow" ng-click="selectPerson()">Person</button>
    </div>

    <div class="ui input" ng-keypress="submit()">
      <input id="businessID" type="text" ng-autocomplete ng-model="autocomplete">
    </div>


    <div class="submit">
      <button class="ui button" id="submit" ng-click="addPayee()">
        <i class="arrow right icon"></i>
      </button>
    </div>

  </div>

  <div class="search"></div>


  <div class="payments" ng-controller="paymentController">
    <li ng-repeat="newPayee in payees">{{payees}}</li>
  </div>

  <!-- <topbar></topbar> -->

</div>

(example template) businessTemplate.html:

 <div class="Business">
   <div class="BusinessName" id="name">{{businessID}}</div>
   <div class="Address" id="address">{{address}}</div>
   <button class="ui icon button" id="hoverbox">
     <i class="dollar icon"></i>
   </button>
 </div>



via Chebli Mohamed

Is there a way to remove the extra wrapping div around a CollectionView in Marionette js 2.x?

I see ways to remove from ItemViews and Layouts but not the CollectionView. Override attachHTML? Using the CollectionView's tagName property to target an element won't work for me because I need the collection items to render directly into an already existing DOM element, not a new one generated by the CollectionView.



via Chebli Mohamed

FB change share location

How can I make "In a private message" value by default? I think this value affects "action_type", found only this example:

  FB.ui({
    method: 'share_open_graph',
    action_type: 'og.likes',
    action_properties: JSON.stringify({
      object:'http://ift.tt/1nt9Vwm',
    })
  })

share dialog

I know about FB.ui({method: 'send'}), but I need share dialog with "In a private message" by default.



via Chebli Mohamed

Get First line in Summernote

i can't get the first line of text using Summernote WYSIWYG Editor, i try using indexof of last
but not work.

how could you do this?

Thx.



via Chebli Mohamed