Saturday, September 30, 2017

Why I should extract three times the infromation from Facebook crawler to get my site information

I have a site made with AngularJS where in order to get the right information from Facebook to share the link, I need to go first to Facebook crawler and extract the information three times before getting the right data.

The first time, I get the default information
The second time I get the title and the description of the specific page, but not the image.
The third time I get the full information (including the image).

But as the site allow the user to upload information and create dinamically new pages, if they try to share the deepling they won’t get all the information at least they go to Facebook scrawler and make it search the page three times…

Im’m using prerender to get the page dinamic information

The page is for example: https://www.granojo.com/video/10403

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/why-i-should-extract-three-times-the-infromation-from-facebook-crawler-to-get-my-site-information/
via @lzomedia #developer #freelance #web #lzomedia.com

Appending a list iterating in AngularJS to the HTML DOM

So I have an AngularJS function that when called should add a list element to a div in the DOM, and the list should be ng-repeat so that it could iterate on objects from a list.

These objects in the list contain a few properties which I want to print out.

Part of the AngularJS program

var el = angular.element(document.getElementById('categories'));
el.append('<ul id="' + categoryItemStr + '"><li ng-repeat="item in categories[currentCategory]"><h4 class="h4"></h4><br><span style="font-size:11px;">.00 $</span></li></ul>');

But when I run it it’s not ng-repeatable and it looks like the javascript hasn’t rendered. It’s important to note that I have the same HTML already in the document when the page loads and it works fine when it doesn’t come out of an angular function but is written inside the HTML document.

How do I fix this?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/appending-a-list-iterating-in-angularjs-to-the-html-dom/
via @lzomedia #developer #freelance #web #lzomedia.com

angularjs: Error: Firebase Database (4.3.1) INTERNAL ASSERT FAILED: Missing index implementation for isEmpty

I try to read some data from firebase, but my logic doesn’t work..
the problem seems to occur when I create a database ref.

my lib version:
AngularJS v1.6.5
AngularFire v2.3.0
Firebase v4.3.1

My firebase db:

{
  "post" : [ null, {
    "message" : "hi",
    "name" : "Mario Rossi"
  }, {
    "message" : "hi",
    "name" : "Alessia Gallina"
  }, {
    "message" : "hi",
    "name" : "Stefano Macchi"
  }, {
    "message" : "hi",
    "name" : "Roberto Singapore"
  }, {
    "message" : "hi",
    "name" : "Elena Soghi"
  }, {
    "message" : "hi",
    "name" : "Bet Bet"
  } ]
}

my controller:

(function () {
    'use strict';

    angular.module( 'messenger' )
        .controller('fireGetPost', [ 'FIREBASE','$scope','$firebaseArray',  function(FIREBASE, $scope, $firebaseArray) {
            var vm = this;
            vm.data = [];

            // Init firebase ap
            firebase.initializeApp(
                FIREBASE.config()
            );

            var ref = firebase.database().ref();
            var posts = ref.child("post");
            $scope.posts = new $firebaseArray(posts);


        }]);

})();

my html:

<md-content ng-controller="fireGetPost as controller" layout="column" class="showcase">

    <md-virtual-repeat-container id="vertical-container" flex>


        <div ng-repeat="data in controller.posts">

            <md-content class="md-padding" layout-xs="column" layout="row">

                <div flex-xs flex-gt-xs="50" layout="column">

                    <md-card class="card" md-theme="" md-theme-watch>


                        <md-card-content>
                            <p></p>
                        </md-card-content>


                    </md-card>

                </div>
            </md-content>

        </div>


    </md-virtual-repeat-container>

and the output console is:

Error: Firebase Database (4.3.1) INTERNAL ASSERT FAILED: Missing index implementation for isEmpty
    at o (libs.min.js:773)
    at i (libs.min.js:773)
    at libs.min.js:773
    at h (libs.min.js:773)
    at t.addToIndexes (libs.min.js:773)
    at t.updateImmediateChild (libs.min.js:773)
    at t.updateChild (libs.min.js:773)
    at t.updateChild (libs.min.js:773)
    at t.updateSnapshot (libs.min.js:773)
    at t.Ri (libs.min.js:773) "<main data-ng-view="" class="ng-scope" data-ng-animate="1">"

Thanks in advance!!

ps. naturally, my bundle includes:
[ ‘ngRoute’, ‘ngMaterial’, ‘ngCookies’, ‘firebase’ ]

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/angularjs-error-firebase-database-4-3-1-internal-assert-failed-missing-index-implementation-for-isempty/
via @lzomedia #developer #freelance #web #lzomedia.com

Can we use J hipster to develop android app?

I am new to develop android application, I have to develop android application with J-Hipster, so is this possible to develop android application with J-Hipster ?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/can-we-use-j-hipster-to-develop-android-app/
via @lzomedia #developer #freelance #web #lzomedia.com

How to attach event to dom created in link function

I know that dom created in template function can be attached to an event in controller.As:

angular.module('app', [])
  .directive('appClick', function(){
     return {
       restrict: 'A',
       scope: true,
       template: '<button ng-click="click()">Click me</button> Clicked  times',
       controller: function($scope, $element){
         $scope.clicked = 0;
         $scope.click = function(){
           $scope.clicked++
         }
       }
     }
   });

As there is no scope in template so I have to use link function.
The same how can I achieve in link function. Like:

 angular.module('app', [])
      .directive('appClick', function(){
         return {
           restrict: 'A',
           scope: true,
           link:function(scope, element, attrs){
  element.html('<button ng-click="click()">Click me</button> Clicked  times')
},
           controller: function($scope, $element){
             $scope.clicked = 0;
             $scope.click = function(){
               $scope.clicked++
             }
           }
         }
       });

How to attach event here.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/how-to-attach-event-to-dom-created-in-link-function/
via @lzomedia #developer #freelance #web #lzomedia.com

How to get a value out of an array in typescript?

I have an array that looks like this

   const array: any[] = []
   array.push({ 'Comments': this.comment, 'Name': this.name, 'Description' : this.description })

I pass that array back to a parent component. How can I grab the value that is in Comments?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/how-to-get-a-value-out-of-an-array-in-typescript/
via @lzomedia #developer #freelance #web #lzomedia.com

How to change only specific color of radio button in angular?

I have crated angular application for examination in which user gives exam and finally show full report with selected answer I have used ng-repeat for radio button to show options and I want to show user has selected answer and corrected answer if user has selected wrong than its should be red else green but it I have checked using conditions but it changing all radio button colors here is code

<div class="md-radio"
             data-ng-repeat="data in vm.examQuestions.allOptions track by $index"
             ng-class="{correct:vm.examQuestions.attemptQuestions.yourChoice === vm.examQuestions.correctanswer ||
             vm.examQuestions.correctanswer === vm.optionsArr[$index],
        'has-error':vm.examQuestions.attemptQuestions.yourChoice !== vm.examQuestions.correctanswer}">
            <span class="lblOption"></span>
            <input type="radio" id="" name="radio" class="md-radiobtn"
                   ng-model="vm.examQuestions.attemptQuestions.yourChoice"
                   ng-value="vm.optionsArr[$index]"
                   ng-disabled="true">
            <label for="">
                <span class="inc"></span>
                <span class="check"></span>
                <span class="box"></span>
                <label ng-if="'string' === vm.checkOptionString(data);"></label>
                <img ng-src="" ng-if="'URL' === vm.checkOptionString(data);" width="40px">
            </label>

can someone tell me how to apply color only to specific radio button if user has selected right or wrong options
thanks in advance

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/how-to-change-only-specific-color-of-radio-button-in-angular/
via @lzomedia #developer #freelance #web #lzomedia.com

AngularJS login two different files

I have 2 files, one you have to login and the other one you are logged in.

This is the form login:

var monarchApp = angular.module('monarchApp', ['ngRoute']);
  monarchApp.controller('loginController', function($scope, $rootScope, $location){
    $scope.username = "admin";
    $scope.password = "pass";
    if($scope.username == "admin" && $scope.password == 'pass'){
      $rootScope.loginStatus = true;
      console.log($rootScope.loginStatus);
      window.location.replace('main.html');
    }
  });

But when I’m at the Main.html is can’t find the $rootScope.loginStatus.
I thing the problem is window.location.replace(); that he does not take the rootScopes with him.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/angularjs-login-two-different-files/
via @lzomedia #developer #freelance #web #lzomedia.com

AngularJS Upload image sending post through $http function

I recently tried to code an upload script which is not really working as it should. The goal is to send a Picture through POST method, using the $http function built in AngularJS.
So I’m basically using AngularJS to get datas from my own API REST and insert them to the dom, my front server and my back server are separated.

But as i want to upload my files directly on the front server, where you only get the DOM features, i decided to create a small script outside my API called upload.php, a little bit like that:
./index.php (get datas and show templates)
./upload.php (upload data)

But here is the trick. My PHP file is a module outside my main framework, which is the only real php script on my front server. It’s working fine, but When i try to use it in background with some js, everything goes wrong. I can’t send datas, or I’m receiving something php cannot read.

It’s starting to mess with my minds as I learned JS all by myself with no outside help.

So here is the PHP script, there is one thing I’m absolutely 100% sure of: I’m not getting the right data of that php://input and I may need to remove this json_decode as I’m maybe not receiving json but POST… I don’t know, I’m so deep lost. And my angular Function, wich is maybe sending things not the right way too. I’m here to learn some more. But please do not try to reinvent the wheel unless it’s really necessary. I’m certain I can do things maybe slightly better, but i have my ways, and i’m willing to go throught another, only if i see something really necessary. Here it is:

<?php
$received_data          = file_get_contents("php://input");
$dataJsonDecode         = json_decode($received_data);

if(isset($dataJsonDecode->packet) && $dataJsonDecode->packet === true) {
  $checker = true;
  $mess= "The following informations are incorrect: <br />";

  if(isset($dataJsonDecode->id) && $dataJsonDecode->id !== null) {
    if(preg_match("#^[0-9]{1,11}$#", $dataJsonDecode->id)) {
      $post1 = $dataJsonDecode->id;
    } else {
      $checker = false;
      $mess .= "- Wrong ID,<br />";
    }
  } else {
    $checker = false;
    $mess .= "- Empty ID,<br />";
  }

  if(!isset($post1)) {
    $post1 = null;
    $checker = false;
    $mess .= "- False ID,<br />";
  }
  $mess .= "Please check at your ID, then try again.";

  if($checker === true) {
    // Constantes
    define('TARGET', '../solocal/img/showcases/');
    define('MAX_SIZE', 100000);
    define('WIDTH_MAX', 800);
    define('HEIGHT_MAX', 800);

    $tabExt = array('jpg','gif','png','jpeg'); 
    $infosImg = array();

    $extension = '';
    $message = '';
    $nomImage = '';
    if(is_dir(TARGET) ) {
      if(!is_dir(TARGET.$post1."/") ) {
        if(!mkdir(TARGET.$post1."/", 0755) ) {
          $attempt = false;
          $message = 'Error: the directory could not be created';
        }
      }
    }

    if(!empty($dataJsonDecode->fichier)) {
      if(!empty($dataJsonDecode->fichier["name"]) ) {
        $extension  = pathinfo($dataJsonDecode->fichier->name, PATHINFO_EXTENSION);

        if(in_array(strtolower($extension),$tabExt)) {
          $infosImg = getimagesize($dataJsonDecode->fichier->tmp_name);

          if($infosImg[2] >= 1 && $infosImg[2] <= 14) {
            if(isset($dataJsonDecode->fichier->error) && UPLOAD_ERR_OK === $dataJsonDecode->fichier->error) {
              $nomImage = 'cover.'. $extension;

              if(move_uploaded_file($dataJsonDecode->fichier->tmp_name, TARGET.$nomImage)) {
                $attempt = true;
                $message = 'Uploaded with success !';
              } else {
                $attempt = false;
                $message = 'An intern error messed it up we are sorry, but you need to upload your file again...';
              }
            } else {
              $attempt = false;
              $message = 'An intern error messed it up we are sorry, but you need to upload your file again...';
            }
          } else {
            $attempt = false;
            $message = 'This file is not a picture !';
          }
        } else {
          $attempt = false;
          $message = 'The file extension is not allowed !';
        }
      } else {
        $attempt = false;
        $message = 'Please fill up the form !';
      }
    } else {
      $attempt = false;
      $message = 'Please fill up the form !';
    }
  } else {
    $attempt = false;
    $message = $mess;
  }
} else {
  $attempt = false;
  $message = 'No datas sent !';
}

$array = array(
  "attempt" => $attempt,
  "message" => $message
  );

echo json_encode($array);
?>

Here is the function i use to read and send this file:

$scope.uploadCover = function(id) {
    var fichier = document.getElementById('fichier').files[0];
    var lecture = new FileReader();
    lecture.onloadend = function(evenement){
    var donnees = evenement.target.result;
        $scope.module.upload = {};
        type_id = typeof id;
        $scope.module.upload.id = type_id.toString();

        if($scope.module.upload.id !== 'undefined' && id !== false && id !== null) { $scope.setter = true; } else { $scope.setter = false; };

        if($scope.setter !== false) {
            $http({
                method: 'POST',
                url: 'http://localhost/dev/goomreactorinterface/admin/upload.php',
                data: {
                    packet: true,
                    id: id,
                    fichier: donnees
                },
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function successCallback(responsemod) {
                $scope.module.upload.results                = responsemod.data;
                console.log($scope.module.upload.results);
                if($scope.module.upload.results.API) {
                    $scope.module.upload.error          = false;
                    $scope.module.upload.html_message = $sce.trustAsHtml($scope.module.upload.message);
                } else {
                    $scope.module.upload.error = true;
                };
            }, function errorCallback(responsemod) {
                $scope.module.upload.error          = true;
            });
    };
    }
    lecture.readAsBinaryString(fichier);
    $scope.result = null;
    $scope.loadAPI();
};

So i thank you all in advance for your participation, I really hope you i can have a pretty constructive feed.

Peace

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/angularjs-upload-image-sending-post-through-http-function/
via @lzomedia #developer #freelance #web #lzomedia.com

Node delivering same js files repeatedly

I am developing a node application using express. I have a index.html file which has path of all js files which is delivered using express. I have written a directive navigation for nav bar. Whenever I am using navigation directive express is continuously delivering same files repeatedly.But this problem does not happen when I do not use directive. I am not able to figure out why it is happening. Here is directive for navigation

(function () {
angular.module('wp').directive('navigation', navigation);

function navigation() {
    return {
        restrict: 'EA',
        templateUrl: '/commons/directive/navigation/nav.template.html',
        controller: 'navigationCtrl as navvm'
    };
}

})();

navigationCtrl:

 (function () {
  angular.module('wp').controller('navigationCtrl',['$location', 'authentication',
  function($location, authentication) {
      var vm = this;

      vm.isLoggedIn = authentication.isLoggedIn();
      /*if not logged in redirect to login page*/
      if(!vm.isLoggedIn) {
        $location.path('/');
      } else {
        vm.currentUser = authentication.currentUser();
      }

      vm.logout = function() {
          authentication.logout();
          $location.path('/');
      };
  }]);
})();

template:

<div class="navbar navbar-Default">
  <div class="container-fluid">
    <ul class="nav nav-tabs">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" style= "font-size:30px;padding-left:60px" href="#"><b><font color="orange">W</font><font color="#00bfff">P</font></b></a>
      </div>
      <div class="collapse navbar-collapse " id="myNavbar">
        <ul class="nav navbar-nav navbar-left ">
          <form class="navbar-form" role="search">
            <div class="form-group">
              <input  class="form-control" style="width:350px; margin-top:5px; " placeholder="Search people">
            </div>
          </form>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li ng-if="navvm.isLoggedIn"><a href=""></a></li>
          <li><a href="" ng-click="navvm.logout()">Logout</a></li>
          <li><a href="Home.html">Home</a></li>
          <li><a href="Explore.html">Explore</a></li>
          <li><a href="Nodes.html">Nodes</a></li>
          <li><a href="message_pop.html">Messages</a></li>
          <li><a href="MyPitch.html"><span class="glyphicon glyphicon-log-in"></span> Profile </a></li>
        </ul>
      </div>
    </ul>
  </div>
</div>

And following is app.js file

    require('dotenv').load() ;
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');

require('./app_api/models/db');
require('./app_api/config/passport');

var routesAPI = require('./app_api/routes/index');
//var verify = require('./app_server/verify');

var app = express();

// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'app_client')));
app.use(passport.initialize());
app.use('/api', routesAPI);
//app.use('/verify', verify);
app.use(function(req, res) {
  console.log("success");
    res.sendFile(path.join(__dirname, 'app_client', 'index.html'));
});


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/30/node-delivering-same-js-files-repeatedly/
via @lzomedia #developer #freelance #web #lzomedia.com

Friday, September 29, 2017

Using $rootScope and $broadcast to communicate between functions

In my app I have one page that shows the details of a particular users document in which a document can be deleted and another that shows the users recently viewed documents. I’m trying to make it so when a user deletes a document in the view page it also deletes the listing in the users recently viewed documents history.

I’m attempting to use $broadcast and $rootScope to communicate between the two modules but I suspect I’m doing something wrong with the syntax or there’s an issue with scope or project structure.

Here’s the two separate functions that delete the different entries

history.js

//gets the selected item the user clicks and deletes it and updates history
$scope.removeFavorite = function(item) {
  var items = $scope.recent[item.type];

  item = items.splice(items.indexOf(item), 1)[0];

  $rootScope.$on('deleteRecent', function(data) {
    historyManager.remove(data);
  });

  historyManager.remove(item).then(loadHistoryItems, loadHistoryItems);
};

documentView.js

//confirmation that user wants selected document deleted
function confirmDelete() {
  var delObj = _.pick(sDocument, 'Doc_Type', 'Doc_Num');

  repos
    .sDoc
    .del(delObj);

  var item = sDocument.Doc_Type + ';' + sDocument.Doc_Num;

  $rootScope.$broadcast('deleteRecent', item);

  tabBarViewModel.removeTabByState($state.get('sDocument'), delObj);

  $scope.modalOptions.hide();
}

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/using-rootscope-and-broadcast-to-communicate-between-functions/
via @lzomedia #developer #freelance #web #lzomedia.com

Ionic 3: ng-change doesn’t work

I have a input field where a user can input his address and get auto-suggestions:

 <ion-label color="primary" stacked>Adresse:</ion-label>
        <ion-input type="text" ng-model="autocomplete.query" ng-change="updateSearch()"></ion-input>

My class has a update method where i want to do something, but unfortunately he doesn’t get into it.

updateSearch()
  {
    console.log('aaa');
    if (this.autocomplete.query == '') {
      this.autocompleteItems = [];
      return;
    }
}

Any ideas?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/ionic-3-ng-change-doesnt-work/
via @lzomedia #developer #freelance #web #lzomedia.com

flipping issue..initially it loads back side.. I want to load flip-front side first

<div class="row">
        <div class="flex-match-height">
          <div class="col-sm-12 col-md-6>
            <flip flipped="ctrl.toggleFlip">  
              <div class="flip-front">
                  <tile>
                    <tile-tabset>
                      <tile-tab title="A">
                        <customer-detail external-data="something"></customer-detail>
                      </tile-tab>
                      <tile-tab title="B">
                        <co-customer external-data="something"></co-customer>
                      </tile-tab>
                      <div class="icons pull-right">
                        <a href="javascript:void(0)" class="btn btn-icon" ng-click="ctrl.handleFlip($event)" title="C">
                            <i class="material-icons" aria-hidden="true">more_vert</i>
                        </a>
                      </div>
                    </tile-tabset>
                  </tile>
              </div>
              <div class="flip-back">
                 <tile>
                    <div class="row">
                      <div class="col-sm-12">
                        <div class="header-back">
                          <a href="javascript:void(0)" ng-click="ctrl.handleFlip($event)" title="D">
                              <i class="material-icons" aria-hidden="true">close</i>
                          </a>
                          <h1 class="title ng-binding">D</h1>
                        </div>
                      </div>
                    </div>
                    <customer-back external-data="somethihng"
         on-click-configure="ctrl.handleFlip($event)"></customer-back>
                 </tile>
              </div>
            </flip>
         </div>

My flip-back side is loading first initially when page load for 1-2 seconds and then it loads flip-front side. I want to load flip-front initially instead of flip-back. When I click it should show me flip-back…
please can anybody help me I am stuck….
thanks….

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/flipping-issue-initially-it-loads-back-side-i-want-to-load-flip-front-side-first/
via @lzomedia #developer #freelance #web #lzomedia.com

How to customize tooltip on mouse hover of a polar area chart of Angular Charts

I have a polar area chart built with Angular Chart, as it follows:

Polar area chart

I need to customize what’s written in the tooltip mouse hover (Right now it shows [label: value], or [MBA010: 98.69], as in the image), or remove that option completely.

I have tried applying the options as shown in this plunker, supplied by a similar question:

// Controller
$scope.chart_options = {
  tooltipTemplate: function(label) {
    return label.label + ':' + label.value;
  }
};

<!-- View -->
<canvas class="chart chart-polar-area" 
               chart-data="module.data" 
               chart-labels="module.labels" 
               chart-options="chart_options"></canvas>

But these options don’t work on the polar area chart, although it works on all the other chart types.

How can I customize, or remove, tooltips on mouse hover for this particular chart?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/how-to-customize-tooltip-on-mouse-hover-of-a-polar-area-chart-of-angular-charts/
via @lzomedia #developer #freelance #web #lzomedia.com

Can’t find role when adding user to role in Asp.Net API Controller?

So, just when I finally thought I had understood the Microsoft Asp.Net Identity Role System … I run into a new problem…

I have a working controller that does my role management but I had problems in the view so I decided to use angularjs for my Web-Apps Admin-Panel.

Everything seemed to work after a bit of hacking but now I’m at a point that I don’t understand at all. My process:

  • Admin presses a button, which passes a user ID (string) to an angular Controller.
  • Angular makes a POST Request to my ApiController, passing the userID to a Controller action that is supposed to authorize my user.

Here is my API Controller:

public async Task<IHttpActionResult> changeAuth()
    {
        string userID;
        var requestData = HttpContext.Current.Request.InputStream;
        using (StreamReader sr = new StreamReader(requestData))
        {
            userID = sr.ReadToEnd();
        }
        Models.ApplicationUser user;
        try
        {
            user = await UserManager.FindByIdAsync(userID);
            if (user == null)
                throw(new Exception());
        }
        catch(Exception ex)
        {
            return BadRequest("couldn't find user in db");
        }
            foreach(var role in user.Roles)
            {
                testlist.Add(RoleManager.FindById(role.RoleId).Name);
            }
            if (!IsUserInRole(user, authRole))
            {
                IdentityResult res = new IdentityResult();
                try
                {
                    res = await UserManager.AddToRoleAsync(user.Id, authRole.Id);
                }
                catch(Exception ex)
                {
                    return BadRequest(ex);
                }
            }
            if(IsUserInRole(user, authRole)
                return Ok("User is now authorized!");
            else
                return InternalServerError("Adding User to Role failed");
    }

  • I load the userID (which works)
  • I load the user, UserManager that I got from HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
  • I do the same thing with the respective Role (-> authRole), both of these are found and I can see their values in the debugger.
  • User doesn’t have the role yet, so I execute ´await UserManager.AddToRoleAsync(user.Id, authRole.Id);`… and get an exception:

Exception: System.InvalidOperationException: The Role "50ab556b-a8e4-4294-b91c-1f9374c25244" does not exist at Microsoft.AspNet.Identity.EntityFramework.UserStore`6.<AddToRoleAsync>d__3b.MoveNext()

I have no clue why this is happening. Is it the fact that I’m using a WebAPI Controller instead of regular? Maybe because I use HttpContext.Current.GetOwinContext() instead of HttpContext.GetOwinContext() to load the User/Role Manager? But if there’s something wrong with Role-/Usermanager … how does it find the user and the role when I search for it, only when I try to add the user to the role it doesn’t work? AddToRoleAsync is the very same method I used just today, when I registered my TestUsers to add the role “NewUser” to them …

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/cant-find-role-when-adding-user-to-role-in-asp-net-api-controller/
via @lzomedia #developer #freelance #web #lzomedia.com

ng-show working with multiple filters in ng-repeat

I have an ng-repeat list with multiple filters, but as I need the elements to be hidden and not removed from the DOM, I use ng-show for the filtering.

This is how my first filter look like:

<a href="" ng-click="myFilter = ''; toggle = toggle=0; togglesec=0; mySecondFilter = {}" ng-class="{'active' : toggle==0}" >
   Tot
</a>

<a href="" ng-click="myFilter = 'pa'; toggle = toggle=1;  togglesec=0;  mySecondFilter = {}" ng-class="{'active' : toggle==1}">
   Pa
</a>

<a href="" ng-click="myFilter = 'Reposteria'; toggle = toggle=2; togglesec=0; mySecondFilter = {}" ng-class="{'active' : toggle==2}">
   Reposteria
</a>

And the second one:

<div ng-init="togglesec=0; mySecondFilter = {}">
   <a ng-click="mySecondFilter = {}; togglesec = togglesec=0" ng-class="{'active' : togglesec==0}">
       All
   </a>
   <a ng-click="mySecondFilter = {'vegan': true}; togglesec = togglesec=1" ng-class="{'active' : togglesec==1}">
       Vegan
   </a>
   <a ng-click="mySecondFilter = {'gluten': true}; togglesec = togglesec=2" ng-class="{'active' : togglesec==2}">
       Gluten Free
   </a>
</div>

Now, I was able to filter the ng-repeat using ng-show and the first filter like so:

<div ng-repeat="pa in products" ng-show="pa.tipus.indexOf(myFilter) != -1">

Basically it compares the value of myFilter with the pa.tipus object property, and it works OK.

But it won’t work with the second filter, because mySecondFilter is an object, not a string (it needs to filter the results containing vegan:true or gluten:true)

Here’s an example of my object type:

pa {
    tipus : 'pa',
    gluten : false,
    vegan : true
}

Any tips on how to combine both filters in the same ng-show?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/ng-show-working-with-multiple-filters-in-ng-repeat/
via @lzomedia #developer #freelance #web #lzomedia.com

Basic behavior of protractor with functions outside of the it block

I tried to source one function out in protractor so that it is outside of the it-block. Before the “outsourcing” it worked fine.

That’s my Code:

it('should delete a private linked clone', function () {
            let countPrivateLinkedClonesBefore;
            let countPrivateLinkedClonesAfter;
            vmPortal.navigationbar.navPersonalClients.click();

            countPrivateLinkedClonesBefore = countPrivateLinkedClones();

            console.log(Count of private linked Clones before elimination: ', countPrivateLinkedClonesBefore);

            vmPortal.personalClients.firstLinkedCloneRow.element(by.css('button.btn-danger')).click();
            vmPortal.modalCreateMachine.btnModalDeleteMachine.click();

            countPrivateLinkedClonesAfter = countPrivateLinkedClones();
            console.log('Count of private linked Clones after elimination: ', countPrivateLinkedClonesBefore);
            expect(countPrivateLinkedClonesAfter === countPrivateLinkedClonesBefore - 1);
 });

so my function is countPrivateLinkedClones()

    countPrivateLinkedClones =  function () {
                let countPLC;

                vmPortal.personalClients.linkedCloneList.count().then(function (count) {
                    console.log("Count of private linked Clones:", count)
                    countPLC = count;
                });
                return countPLC;
}

If I run this the result is:

.Count of private linked Clones before elimination: undefined

Count of private linked Clones after elimination: undefined

Count of private linked Clones: 3

Count of private linked Clones: 2

What is the reason for this behavior?

How to fix it, so that the function is not executed at the end instead of where i want to have it executed?

Thanks in advance!

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/basic-behavior-of-protractor-with-functions-outside-of-the-it-block/
via @lzomedia #developer #freelance #web #lzomedia.com

A more object oriented Angular 1.5+ component

I can’t use Angular 2 where I am, but I like how it’s more object oriented (components are classes). We are starting to use Angular 1.5+ components and to eventually ease transition I was looking at using the new javascript functionality of classes to make components classes with Angular 1.5+. Partially just messing around here as well to see what I can come up with.

The specific question I have is that when I define $onInit by setting it to a class function it doesn’t get called but when I define it as an anonymous function it does and I’m not 100% sure why. Any help would be great. A generic question would be does anyone have ideas around how to do this simulation of app.component() to javascript class?

class Component {
    constructor(name, templateUrl, bindings, controllerAs) {
        app.component(name, {
            templateUrl: templateUrl,
            bindings: bindings,
            controllerAs: controllerAs,
            controller: this.controller
        });
    }

    controller() {
        console.log("Inside Component controller");
    }
}

class ListNames extends Component {
    constructor() {
        super("listNames", "ListNames.html", { names: '<' }, "lstNames");
    }

    onInit() {
        console.log("onInit called");
    }

    // overrided method
    controller() {
        console.log("ListNames controller()");
        /*this.$onInit = function () {
            console.log("onInit called");
        }*/
        this.$onInit = this.onInit; // <-- this doesn't work but the above does
    }
}

lstNames = new ListNames();

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/a-more-object-oriented-angular-1-5-component/
via @lzomedia #developer #freelance #web #lzomedia.com

AngularJS – disable if $pristine bug for inputs with pre-filled ng-model values

I have an input field that is pre-filled with a value from an object’s json property using ng-model, and I’m trying to disable a button if this input is either empty initially or if it has an invalid value.

This works, but when the page loads with data already in the input box as a value, the input is treated as being $pristine, because it has not been touched, even though there is a valid value. Therefore, the button, which should be enabled because of the valid value, is still disabled.

I can change the $pristine condition to (personalDetailsForm.niNumber.$pristine && personalDetailsForm.niNumber.$invalid), which correctly enables the button on load when there is a pre-filled value in the input, but if the pre-filled value is removed, the input isn’t treated as being invalid.

Is there any way around this?

HTML:

<div input-field class="input-field col-xs-12 col-sm-6 col-md-2">
    <input id="niNumberInput" name="niNumber" type="text" class="validate" pattern=".{9}" placeholder="" data-ng-model="niNumber">
    <label for="niNumberInput" data-error="National Insurance number must be 9 characters long">National Insurance Number</label>
</div>
<div input-field class="input-field col-xs-12 col-sm-6 col-md-1">
    <button data-ng-click="verifyNINumber()" data-ng-disabled="personalDetailsForm.niNumber.$invalid || personalDetailsForm.niNumber.$pristine" class="btn button waves-effect"><span class="fa fa-search"></span>Verify</button>
</div>

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/angularjs-disable-if-pristine-bug-for-inputs-with-pre-filled-ng-model-values/
via @lzomedia #developer #freelance #web #lzomedia.com

How do I reload an Angular partial for testing purpose?

I use the UI Router module in Angular (1). Typically it would look like

myApp.config(function($stateProvider) {
  var helloState = {
    name: 'hello',
    url: '/hello',
    templateUrl: 'http://www.example.com/partials/helloWorld'
  }
}

Is it possible to reload this partial template forcefully during development where the source code keeps changing? Data changes can be mapped using two-way binding but that is not my scenario? I saw some answers related to the latter case. Is there something like $state.reload('state') kind of functionality?

Is there a better way to test a partial from a development perspective?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/how-do-i-reload-an-angular-partial-for-testing-purpose/
via @lzomedia #developer #freelance #web #lzomedia.com

Augury doesn’t work when angular’s mode is dev

I want to use Augury to debug my angular project, and I have used isDevMode to make sure that the mode is dev, but it doesn’t work. The Augury hint that ‘javascriptThis application is running in production mode and therefore cannot be inspected using Augury.
If this is an Angular application, please rebuild your application in debug mode or remove the call to enableProdMode().

By the way, The project isn’t created by angular cli, and Augury can work well with the project created by angular cli in my browser.
What was wrong ?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/augury-doesnt-work-when-angulars-mode-is-dev/
via @lzomedia #developer #freelance #web

angular 2 this._Router.navigate([‘/app/home’]); navigates to home page but previous page is still on home page

i can navigate properly with “this._Router.navigate([‘/app/home’]);” syntax but it keep all the previous page data on home page.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/angular-2-this-_router-navigateapphome-navigates-to-home-page-but-previous-page-is-still-on-home-page/
via @lzomedia #developer #freelance #web

UI-SELECT does not send data through

I am trying to send data from through but it does not work.
On the other hand, it works with .

Whichmeans,

<input type = "text" ng-model = "customer.selected"/>

is working but not,

<ui-select ng-model="customer.selected" theme="bootstrap">
  <ui-select-match placeholder=""></ui-select-match>
  <ui-select-choices repeat="customer in customers | filter: $select.search">
    <div ng-bind-html="customer.customer_company_name | highlight: $select.search"></div>
  </ui-select-choices>
</ui-select>

I have the controller.js as below which works fine.

$http.post("../crud/projects_insert.php", {
        data_to_go : $scope.customer.selected
})

INPUT works with the controller, but not the data from UI-SELECT.

Does anyone have experienced same issue like this? Maybe I am missing something with UI-SELECT.

The bold written is my question. Please advise me to solve this problem.

Thank you in advance!

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/ui-select-does-not-send-data-through-form/
via @lzomedia #developer #freelance #web

Angular URL SRC in iframe desnt show up

I try to set up an iframe with src to youtube. The url inside an iframe is invisivble, when you inspect element in the browser. The same url pasted outside the iframe works perfectly.

<iframe width="420" height="315" ng-src=""></iframe><br>


you see this when you inspect element

Do you have idea why it happens?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/angular-url-src-in-iframe-desnt-show-up/
via @lzomedia #developer #freelance #web

Way-points – How can i remove a specific way-point from google maps?

I am making this app with the help of google maps, i am successfully adding waypoints in a route and making a route between them. But on dbclick i remove that way point from the map. Now when i make the route it includes the deleted waypoint too. Because of the fact it does not delete from the waypoint array.

The question is how can i remove a specific waypoint from the waypoint array. I dont have any index of something.

pushing waypoints

/* Whenever a user taps a pin it goes into pinwapypts */
        pinwaypts.push({
          location: $scope.destination_route,
          stopover: true,

        });

Add waypoints in map

 infowindow.open($scope.map, marker);
        $scope.markers.push(marker);
        google.maps.event.addListener(marker, 'click', function () {
          infowindow.setContent($scope.results[0].formatted_address);
          infowindow.open($scope.map, this);
        });

removing waypoint marker from map

google.maps.event.addListener(marker, 'dblclick', function () {
          $scope.markers.pop().setMap(null);

        });

Now how can i remove a specific waypoint from its array ?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/way-points-how-can-i-remove-a-specific-way-point-from-google-maps/
via @lzomedia #developer #freelance #web

Why does function in ng-show clause not keep on getting executed on each digest cycle

I am doing a test (while busy solving a different problem)

I have a div element defined as follows:

<div ng-show="myFunction()">
  //some content
</div>

In my controller I have the following JavaScript function:

 $scope.myFunction = function () {
    console.log("myFunction called");
    return true;
 }

I was expecting that in the browser console, when running this code, I will keep on seeing the words “myFunction called” being written over and over and over since I expect the function to be evaluated on each angular digest cycle. But what I am seeing is that it gets called a finite couple of times and then it no longer gets called.

Why is this?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/why-does-function-in-ng-show-clause-not-keep-on-getting-executed-on-each-digest-cycle/
via @lzomedia #developer #freelance #web

Angular popover issue

I am using angular popover to display content in popup. I have multiple records in table, each row contains one button, to click on that button I am displaying a popover. Here my issue is when i click on one button one popover is displaying, next I am clicking on second button second popover is also displaying and two popovers contains second popover content. My requirement is If one popover is already open I am trying to open another one first popover should close. please guide me to implement this requirement.

Thank You,
Java4you.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/angular-popover-issue/
via @lzomedia #developer #freelance #web

Why not use Ionic for web applications rather than responsive Angular? [on hold]

Ionic has in-built grid system, stylish Progressive Web Application based design and angular inspired structure, then why not use Ionic always rather than using Angular (along with bootstrap) to give mobile look and feel?

Using Ionic completely means using Ionic CLI, grid, buttons and all Ionic components.

Thoughts??

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/why-not-use-ionic-for-web-applications-rather-than-responsive-angular-on-hold/
via @lzomedia #developer #freelance #web

Need a folder to be routed making all the contains inside that folder available

Hi guys i need to actually route a folder which will be containing multiple files and folder inside it.

For example 
My folder name is Contains -- with inner folder  sample1 sample2.
sample1 folder contains --  app.js index.js Index.html 
sample2 folder contains --  app.js index.js Index.html

so I want routes for like every file in each folder's 
example --  localhost:3030/Contains/sample1/Index.html
localhost:3030/Contains/sample2/Index.html
localhost:3030/Contains/sample1/index.js
localhost:3030/Contains/sample1/app.js
... etc 

How can I achieve this using stateProvider?

Thanks in advance

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/need-a-folder-to-be-routed-making-all-the-contains-inside-that-folder-available/
via @lzomedia #developer #freelance #web

How to get selected value index dynamically using ng-options in angularjs

I am using select, in which I require selected value and dynamically created index (I don’t want to set default to [0] index)
How it can be done.

        <div class="input-label">
          Select Mobile
        </div>

        <select ng-model="mobile" ng-options="mobile as mobile.value for mobile in editContactModalData.phoneNumbers"></select>
      </label>

    Above is select option and below is input box where the selected value is set       


      <label class="item item-input item-stacked-label" ng-show="mobile">
        <input type="tel" maxlength="10" placeholder="mobile" ng-model="mobile.value">
      </label>

this is one modal and I want to show these changes of selected mobile in another modal

the second modal consist

  <span></span>

so in this in the place of [0] index i want to put dynamically selected value.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/29/how-to-get-selected-value-index-dynamically-using-ng-options-in-angularjs/
via @lzomedia #developer #freelance #web

Thursday, September 28, 2017

Unable to Invoke Angular4’s method from AngularJs?

I am trying to invoke Angualr4’s method by publish event from AngularJs.
I am getting event inside Angular4’s method but not any things live inside
angular4 component everything is undefined, So Unable to perform any activity
in component.

1- public event as:-
         hub.publish('com.xxx.events.xx', id);// from AngularJs file

2- Suscibed here :
         this.hub.subscribe('com.xxx.events.xx', this.onClickCallBack);

    onClickCreateCallBack = function (topic, data) {
            console.log("Type:: "+this);//this object is undefined
            this.openPopup();//Since this is undefined not ivoking openPopup()
      } 

Observations:-

I am booting my Angular4 application by Api call which return all bundles(main bundle, pollyfilles buldle etc..) in form of html response
and I load that response in a div tag.

So here I saw that my Angular4 boot 2 times first when whole environment(AngularJs + other stuffs) boots.

And Second time when I click a Tab Button, here Angular 4 App should be render actually. Here Application launch successfully, but it loss all instance variable ‘s values (becomes undefined).

Note :- Any help would be appreciated.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/unable-to-invoke-angular4s-method-from-angularjs/
via @lzomedia #developer #freelance #web

angularjs scope variables are not working but works on second click

Hi I am developing web application in angularjs. I have implemented print functionality. I am binding values to view using scope variables. When i click first time on print my values are not binding. When i click second time all my values will bind. Below is the print functionality.

 $scope.Print = function () {
                if ($scope.period == null) {
                    toastr.error($filter('translate')('Please select Year.'));
                }
                else {
                $scope.vehiclepriceprint = $cookieStore.get("carpriceprint");
                $scope.downpaymentprint = $cookieStore.get("downpayment");
      }

First time also i will be having values in cookie but not binding to view. Whenever i click second time on print button everything will be working
Below is the print button.

  <input type="button" value="Print" class="blue-button"  ng-click="Print()" id="btnPrint">

Below is the html code of print.

   <span id="lblDownPayment"></span>
   <span id="lblFinancialAmount"></span>

May i know what is the issue i am facing here? Any help would be appreciated. Thank you.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/angularjs-scope-variables-are-not-working-but-works-on-second-click/
via @lzomedia #developer #freelance #web

Spring boot CORS Filter not working with AngularJS

I have created a SpringBoot application which has an AngularJS front-end and I am not using any Spring Security modules.

I have added the @CrossOrigin annotation in my controller as follows

@CrossOrigin(origins = "http://localhost:3000", maxAge = 3600)
@RestController
public class MyController {
   public static final Logger logger = LoggerFactory.getLogger(MyController.class);
   .....
   .....

I have also created a CORS filter as shown below.

@Component
public class CORSFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}
public void destroy() {}

}

I am getting the following error for OPTIONS in my angularJS front-end

XMLHttpRequest cannot load http://localhost:8080/abc/books/. Response for preflight has invalid HTTP status code 401 (edited)

[12:10] 
zone.js:2744 OPTIONS http://localhost:8080/abc/books/ 401 ()

My SpringBoot app works fine with PostMan and this preflight error happens when I use Chrome. How can I fix it?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/spring-boot-cors-filter-not-working-with-angularjs/
via @lzomedia #developer #freelance #web

Loading address data into google maps from database using Angularjs

I am using angularjs for my application.I am trying to load the address from user_address table in database and display it on map on load.

Here is the script i am using to load google maps

    <script async defer src="https://maps.googleapis.com/maps/api/js?
    key=myKey&callback=initMap">
    </script>

Here is the html

    <div id="map"></div>
    <div id="repeatmap" data-ng-repeat="marker in markers | orderBy :
    'title'">
    <a id="country_container" href="#" ng-
    click="openInfoWindow($event, marker)">
    <label id="namesformap" ></label></a>
    </div>

Here is the Controller.js

    var mapOptions = {
        zoom: 4,
        center: new google.maps.LatLng(25,80),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    }

    $scope.map = new google.maps.Map(document.getElementById('map'),
    mapOptions);
    $scope.markers = [];
    var infoWindow = new google.maps.InfoWindow();
    var createMarker = function (info){
    var marker = new google.maps.Marker({
            map: $scope.map,
            position: new google.maps.LatLng(info.lat, info.long),
            title: info.city
     });
     marker.content = '<div class="infoWindowContent">' + info.desc +
     '</div>';
     google.maps.event.addListener(marker, 'click', function(){
     infoWindow.setContent('<h2>' + marker.title + '</h2>' + 
     marker.content);
     infoWindow.open($scope.map, marker);
     });
     $scope.markers.push(marker);
     }  

    for (var i = 0; i < $scope.cities.length; i++){
        createMarker($scope.cities[i]);
    }

    $scope.openInfoWindow = function(e, selectedMarker){
        e.preventDefault();
        google.maps.event.trigger(selectedMarker, 'click');
    }

Here is the data that i am getting from database that is all cities from user_address table

    $scope.getAllCities = function()
    {
        DirectoryService.getAllCities().then(function(response){
        $scope.cities = response.data;
        console.log($scope.cities);
    })
    }

As you can see in console i am able to get the response from database but i am not able to get $scope.cities value to for loop.It is saying Cannot read property ‘length’ of undefined.Can anyone tell how can i get value of $scope.cities into for loop so that in map i can display the cities returned from database.Now i am able to display map but with no cities.I dont know whether it will work or not or am i doing the wrong way?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/loading-address-data-into-google-maps-from-database-using-angularjs/
via @lzomedia #developer #freelance #web

$http.get is not giving response

I’m new to node and angular script. I’m having a function readDetails within my service which gives a GET request.

this.readDetails = function() {
        return $http({
            method: 'GET',
            url: '/getDetails'
        }).then(function(data) {
            return data;
        });
    }

Given below is my server side code.

app.get('/getDetails', function(request, response) {
    fs.readFile('details.json', 'utf8', function(err, data) {
        if (err) throw err;
        var obj = JSON.parse(data);
        response.send(obj);
        response.end();
    })
})

I don’t get the response from the server. I do not find Why. Suggestions are welcome

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/http-get-is-not-giving-response/
via @lzomedia #developer #freelance #web

populate and refresh html table using socket.io

I am making an application on using Node.js and angular as fronthand. There I am getting one text file which is log information of users and continously growing. The data is as below,

13:24:24:007,Peter,male,3720,yes
13:24:24:007,John,male,1520,yes
13:24:24:023,John,male,9720,yes
13:24:24:023,Mario,male,9820,no
13:24:24:023,Katy,female,4320,no
13:24:24:038,John,male,3620,no
.....
.....

I want to show the aggregate report data in table format to the client html page for dashboard kind of thing as below.

username    firstlogin  lastglogin  minamount   maxamount
Peter   13:24:24:007    13:24:24:007    3720    3720
John    13:24:24:007    13:24:24:038    1520    3620
Mario   13:24:24:023    13:24:24:023    9820    9820

I am using socket.io to fetch data from server to client. Currently I am making aggregate data in two dimentional array and sending that compelete array to client. At client side, formating that array to display on html page. The problem is, i am sending entire array even for a small change in one users. Thie table may be a big table with 100-200 records. I personally believe this is not right approach. There must be some better way to do this as it overloading the network traffic unnecessarily. Please suggest me some better approach where only changed data is sent to client. If there is change in only one cell, (Peter’s last login) , only that cell data to be sent to via socket and refresh on html table.

Thanks

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/populate-and-refresh-html-table-using-socket-io/
via @lzomedia #developer #freelance #web

Using angular-js ng-disabled

I have this requirement where i need to disable a button based on some condition:

Controller:

<div  ng-controller= "myController" class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"   aria-hidden="true">×</button>
                    <h3 class="modal-title"> Add</h4>

I need to disable this button when I have added 5 entries in html page.Can someone help me out?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/using-angular-js-ng-disabled/
via @lzomedia #developer #freelance #web

Cannot call beforeEach ‘inject’ on angularJS (FUSE Admin) unit testing using karma

I used FUSE Admin app on my project – http://fuse-angular-material.withinpixels.com/apps/dashboards/project.

I already checked other samples and even run this code on a different project and works just fine. IT’s just that I cannot inject the service, controller etc. on ‘beforeEach inject’, thus I cannot cont. my test.

I don’t know what’s wrong or did I miss something (dependencies? not sure) while running this on FUSE. Do you have any idea?

Here’s my code.

SERVICE (the service returns a list of array)

(function () {
    'use strict';

    angular
        .module('app.admin.users', [])
        .config(config)
        .service('adminUserService', service);

    function service(msApi) {
        return {
            adminUserList: function () {
                return msApi.resolve('admin.users.list@query');
            }
        };
    }

    function config(msApiProvider) {
       // calling the API (used dummy data)
        msApiProvider.register('admin.users.list',['app/data/admin/users/users.json']);
    }

})();

UNIT TEST

var oDataService;
var adminUserService;

describe('unit test ----------------------------', function () {
    beforeEach(module('app.admin.users'));

    beforeEach(function () {
        inject(function ($injector) {
            adminUserService = $injector.get('adminUserService');
            oDataService = adminUserService.adminUserList();
        });
    });

    it("is registered with the module.", function () {
        expect(oDataService).not.toBe(null);
    });
});

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/cannot-call-beforeeach-inject-on-angularjs-fuse-admin-unit-testing-using-karma/
via @lzomedia #developer #freelance #web

Angular Js Application Unable Authincate User Login with Wcf Service

I am consuming Wcf Service into Angular Js Application . I have one Boolean function inside the wcf service to accept the username and password. I am trying to create user login system by using Angular Js Application but when I enter the correct username and password its does not working according my expectation. There are no errors showing in Google Chrome console windows.

Here is Interface .

  [OperationContract]
        [WebInvoke(Method = "GET",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        //BodyStyle = WebMessageBodyStyle.WrappedRequest,
        UriTemplate = "/AuthenticateUser")]
        bool AuthenticateUser(UserLogin userLogin);

Here is Implementation ..

 public bool AuthenticateUser(UserLogin userLogin)
        {
            // ConfigurationManager class is in System.Configuration namespace
            string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            // SqlConnection is in System.Data.SqlClient namespace
            using (SqlConnection con = new SqlConnection(CS))
            {
                SqlCommand cmd = new SqlCommand("spAuthenticateUser", con);
                cmd.CommandType = CommandType.StoredProcedure;

                //Formsauthentication is in system.web.security
                string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(userLogin.Password, "SHA1");

                //sqlparameter is in System.Data namespace
                SqlParameter paramUsername = new SqlParameter("@UserName", userLogin.Username);
                SqlParameter paramPassword = new SqlParameter("@Password", encryptedpassword);

                cmd.Parameters.Add(paramUsername);
                cmd.Parameters.Add(paramPassword);

                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    int RetryAttempts = Convert.ToInt32(rdr["RetryAttempts"]);
                    if (Convert.ToBoolean(rdr["AccountLocked"]))
                    {
                        return true;
                    }
                    else if (RetryAttempts > 0)
                    {
                        int AttemptsLeft = (4 - RetryAttempts);
                        //lblMessage.Text = "Invalid user name and/or password. " +
                        //    AttemptsLeft.ToString() + "attempt(s) left";
                    }
                    else if (Convert.ToBoolean(rdr["Authenticated"]))
                    {
                        return true;
                    }

                }
                return false;
            }
        }

Here is Script code .

///// <reference path="../angular.min.js" />  



var app = angular.module("WebClientModule", [])

    .controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {

        $scope.OperType = 1;

        //1 Mean New Entry  

        //To Clear all input controls.  
        function ClearModels() {
            $scope.OperType = 1;
            $scope.Username = "";
            $scope.Password = "";


        }


        $scope.login = function () {
            var User = {
                Username: $scope.Username,
                Password: $scope.Password,


            };
            if ($scope.OperType === 1) {
                var promisePost = myService.get(User);
                promisePost.then(function (pl) {
                    $scope.Id = pl.data.Id;
                    window.location.href = "/Login/WelcomePage";

                    ClearModels();
                }, function (err) {
                    $scope.msg = "Password Incorrect !";
                    console.log("Some error Occured" + err);
                });
            } 

        };



    }]);

app.service("myService", function ($http) {
    //Create new record  

    this.AuthenticateUser = function () {
        return $http.get("http://localhost:52098/HalifaxIISService.svc/AuthenticateUser");
    }


})

Here is the HTML code..

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/RegistrationScript/LoginScript.js"></script>
</head>
<body>
    <table id="tblContainer" data-ng-controller="Web_Client_Controller">
        <tr>
            <td>

            </td>
        </tr>
        <tr>
            <td>
                <div style="color: red;"></div>
                <table style="border: solid 4px Red; padding: 2px;">

                    <tr>
                        <td></td>
                        <td>
                            <span>Username</span>
                        </td>
                        <td>
                            <input type="text" id="username" data-ng-model="Username" required="" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Password</span>
                        </td>
                        <td>
                            <input type="password" id="password" required data-ng-model="Password" require="" />
                        </td>
                    </tr>

                    <tr>
                        <td></td>
                        <td></td>
                        <td>
                            <input type="button" id="login" value="Login" data-ng-click="login()" />

                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
<script src="~/RegistrationScript/LoginScript.js"></script>

Here is the screen shot when I run the application.Click here to see the result

Any Help or suggestion will he highly appreciated.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/angular-js-application-unable-authincate-user-login-with-wcf-service/
via @lzomedia #developer #freelance #web

Ionic 3 app with firebase – How to edit a firebase list observable and make it display correctly in edit page

So I have actually managed to figured out how to edit information from my ionic app and update it to firebase, however i’m trying to figure out how to get the current information from my list observable and display it in the ion-input fields. So when you click on an item you want to edit it opens an edit page and then in the ion-input fields it displays the current information that you can then edit.

Here is my editpage.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, FirebaseObjectObservable } from 
'angularfire2/database';
import { AboutPage } from '../about/about';
import { AngularFireAuth } from 'angularfire2/auth';
import { Todo } from './../../models/todo';

@IonicPage()
@Component({
selector: 'page-editpage',
templateUrl: 'editpage.html',
})
export class EditpagePage {

todoDataRef$: FirebaseObjectObservable<Todo>;
todo = {} as Todo;
 public userId;

constructor(private afAuth: AngularFireAuth, private database: 
AngularFireDatabase, public navCtrl: NavController, public navParams: 
NavParams) 
{

   const todoId = this.navParams.get('todoId');

   console.log(todoId);

   afAuth.authState.subscribe( user => {
   if (user) { this.userId = user.uid }
     this.todoDataRef$ = this.database.object(`todo/${user.uid}/${todoId}`);
   });

 }

 editTodoItem(todo: Todo){
   this.todoDataRef$.update(todo);
   this.navCtrl.pop();
 }

}

here is my editpage.html

<ion-header>

 <ion-navbar>
   <ion-title>Edit Task</ion-title>
 </ion-navbar>

</ion-header>


<ion-content padding>


<ion-item>
    <ion-label floating>Title</ion-label>
    <ion-input [(ngModel)]="todo.Title"></ion-input>
</ion-item>

<ion-item>
    <ion-label floating>Description</ion-label>
    <ion-input [(ngModel)]="todo.Desc"><textarea></textarea></ion-input>
</ion-item>


<button style="margin-top:30px;" ion-button block 
(click)="editTodoItem(todo)">Edit Task</button>

Here you can see the structure of my firebase database. For every user they are given an user.uid and then all their data is placed inside that. I believe that’s the issue but im not sure. So its the TO DO list, then the user.id, then the individual item id.

enter image description here

any suggestions?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/28/ionic-3-app-with-firebase-how-to-edit-a-firebase-list-observable-and-make-it-display-correctly-in-edit-page/
via @lzomedia #developer #freelance #web

Wednesday, September 27, 2017

Custom component holder, which will dynamically create child component with min and max option

My requirement is to create panel with minimize and maximize button.
based on maximize click of any child component only one should occupy whole parent holder container space and remaining should be hidden.

Where I will have customCompoentHolder , in which I will define number of child component. like below

 <my-custom-minmax numOfcompPerRow="2">
    <mycomp1></mycomp1>
    <mycomp2></mycomp2>
    <mycomp3></mycomp3>
 </my-custom-minmax>

Here numOfcompPerRow will tell holder component, that how many child component can render per row, if more are there, it should create new row.

And each child component will have own minimize and maximize button.

I tried my-self to get list of child’s and then try to render.

I am able to get list of child by having custom directive or by having base component. And I have use @Contentchilder, and it works properly.

But creating component or rendering component using this.componentFactoryResolver.resolveComponentFactory() doesn’t working for me.

It’s giving me error ERROR Error: No component factory found for undefined. Did you add it to @NgModule.entryComponents?

This is bit hard to understand for me, how to dynamically create component and re-render on different events.

Anyone have idea , how to implement this minimize and maximize functionality. best possible way in Angular

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/custom-component-holder-which-will-dynamically-create-child-component-with-min-and-max-option/
via @lzomedia #developer #freelance #web

Why grid.appScope.value return undefined in celltemplate

In a grid celltemplate, I am tring the get a value which is in the parent scope of a grid like this

<div sigef-entrees-sorties="grid.getCellValue(row, col)"
type-flux="grid.appScope.typeFlux">
</div>

but grid.appScope.typeFlux is undefined. So how can i get this value.

Thanks.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/why-grid-appscope-value-return-undefined-in-celltemplate/
via @lzomedia #developer #freelance #web

How to test Handsontable with virtual scrolling in Angular App using Protractor?

We use Handsontable in a hybrid AngularJS / Angular app that we test using Protractor. As far as I know we don’t use the available Angular wrapper for Handsontable but instead use it directly.

Typical actions we would like to do in a fast way:

  • Expand all collapsed columns in the table
  • Read value of cell (x,y)
  • Read all values in row y
  • Change the value in cell (x,y)

Currently we have two approaches to test Handsontable components:

  • Using regular CSS selectors to find elements. This is pretty fast. But it only works if the table has no virtual scrolling, so that all elements are actually in the DOM.
  • Using keyboard navigation (up, down, left, right). This also works with virtual scrolling, but it’s very slow.

Do you know any other approaches that can speed up tests especially for larger tables with virtual scrolling? Is there maybe some way to talk to the Handsontable API directly from the Protractor test to scroll / select a certain cell in a table that has virtual scrolling?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/how-to-test-handsontable-with-virtual-scrolling-in-angular-app-using-protractor/
via @lzomedia #developer #freelance #web

Angularfire $firebaseArray extend dynamic countsum

Am trying to achieve a dynamic count of certain node if defined:

This works but its not dynamic, you have to call sum().

app.factory("ArrayWithSum", function($firebaseArray) {
  return $firebaseArray.$extend({
    sum: function() {
       var total = 0;
       var todayDate = new Date();
       var start = todayDate.setHours(0,0,0,0);
       var end = todayDate.setHours(23,59,59,999);

        // the array data is located in this.$list
        angular.forEach(this.$list, function(rec) {
            if (angular.isDefined(rec.qa)){
                if (angular.isDefined(rec.qa.completed)) {
                    if (rec.qa.completed >= start && rec.qa.completed <= end){
                        total++;
                    }
                }
            }

        });
        return total;
    }
  });
});

I tried $$update but can’t access this_counter in array:

  app.factory("counter", function($firebaseArray) {
      return $firebaseArray.$extend({
        sum: function() {
            return this._counter;
        },
        $$updated: function(){

           var changed = $firebaseArray.prototype.$$updated.apply(this, arguments);

           var todayDate = new Date();
           var start = todayDate.setHours(0,0,0,0);
           var end = todayDate.setHours(23,59,59,999);

           if( !this._counter ) { 
               this._counter = 0; 
           }

            // the array data is located in this.$list
            angular.forEach(this.$list, function(rec) {
                if (angular.isDefined(rec.qa)){
                    if (angular.isDefined(rec.qa.completed)) {
                        if (rec.qa.completed >= start && rec.qa.completed <= end){
                            this._counter++;
                        }
                    }
                }

            });
          return changed;
        }
      });
    });

Does anyone know how to make a dynamic variable that I can update and access?

Thanks

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/angularfire-firebasearray-extend-dynamic-countsum/
via @lzomedia #developer #freelance #web

Angularjs $http request using rest api

So, I made a todo list using angularjs and made an api using php slim framework and mysql for task storage.
I’m trying to use the $http service to save/delete/update tasks in the DB and so far, I came up with this (code below) but since I’m no expert in this matter, there’s probably a lot of crucial mistakes.

Keep in mind that, the code regarding the todo list works fine and I’d like some guidance and tips for the $http requests.

JS:

var app = angular.module('todoApp', []);
app.controller('TodoListController', ['$scope', '$http', function ($scope, $http) {
  $scope.todos = [];
  $scope.newField = [];
  $scope.customStyle = {};
  $scope.date = new Date();

  $http({
    method: 'POST',
    url: 'http://taskapi.dev/api/tasks/add' }).then(function successCallback (response) {
      $scope.addTodo = function () {
        $scope.todos.push({text: $scope.todoText, done: false, editing: false, date: new Date()});
        $scope.todoText = '';
      };

      $scope.save = function (index) {
        $scope.todos[index].editing = false;
        $scope.todos[index].createdOn = new Date().getTime();
      };
    });

  $http({
    method: 'PUT',
    url: 'http://taskapi.dev/api/tasks/update' }).then(function successCallback (response) {
      $scope.editTodo = function (todo) {
        todo.editing = true;
      };

      $scope.change = function (field) {
        var todoIndex = $scope.todos.indexOf(field);
        $scope.newField[todoIndex] = angular.copy(field);
        $scope.todos[todoIndex].editing = true;
        $scope.todos[todoIndex].LastModifyOn = new Date().getTime();
      };

      $scope.turnGreen = function (todo) {
        todo.customStyle = {'background': 'green'};
      };

      $scope.turnYellow = function (todo) {
        todo.customStyle = {'background': 'yellow'};
      };

      $scope.turnRed = function (todo) {
        todo.customStyle = {'background': 'red'};
      };

      $scope.cancel = function (index) {
        $scope.todos[index] = $scope.newField[index];
      };
    });

  $http({
    method: 'DELETE',
    url: 'http://taskapi.dev/api/tasks/delete' }).then(function successCallback (response) {
      $scope.delete = function () {
        var oldTodos = $scope.todos;
        $scope.todos = [];
        angular.forEach(oldTodos, function (todo) {
          if (!todo.done) $scope.todos.push(todo);
        });
      };

      $scope.remove = function () {
        $scope.todos.splice(this.$index, 1);
      };
    });
}]);

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/angularjs-http-request-using-rest-api/
via @lzomedia #developer #freelance #web

Angular CRUD to and from API

I am trying to build a system that you upload photos add photos to array, save photos. When you save photo it posts to a API, also the Array is per populated with the current images saved to the API on last visit.

So

  1. User uploads photos and sees a preview (Working)
  2. Click add and it adds the preview image to the array (NOT WORKING FULLY)
  3. Save updated array and post to API. (Working but dose not update array async)

In Summery

I need a array of images that is pulled from a API and the images can be deleted and added then saved back to the API.

Things I need help with

At the moment I print out the array from the API request separately to the array you add the preview image to to display on the front end.

bellow you can see I am getting the base64 from the API and the images added from the preview.

see photo bellow

enter image description here

I need both to be the same, so on load of the page you seen all the images from the API with the delete button next to each image and also when you add image from preview for them to also be with the images from the API but not post to the API and update with new array until click save

My HTML

 <div class="dynamic-upload-container">
            <div class="preview"><img style="height: 100px; width: 100px" ng-src="" alt="preview image"></div>
            <div class="upload-new">
                <input id="fileinput" ng-model="file" type="file" ng-model-instant="" name="file" accept="image/*" onchange="angular.element(this).scope().uploadImage(this)">

            </div>
            <div class="slots-container">
                <table>
                    <tr>
                        <th><p>Campaign Name</p></th>
                        <th> <strong></strong></th>
                    </tr>
                    <tr>
                        <td><p>Max images allowed</p></td>
                        <td><strong></strong></td>
                    </tr>
                    </tr>
                </table>

                <button ng-click="addImage()">Add image</button>

                <h3>these are the images pulled from API</h3>
                <strong></strong>

                <h3>these are the images added from preview</h3>
                    <div ng-repeat="slot in slots"  class="slot">
                        <img ng-click="addImage()" style="height: 100px; width: 100px" ng-src="" alt="slot image">
                        <button ng-click="removeImage(slot)">Remove Image</button>
                </div>

                 <button ng-click="SaveImage()">Save to API</button>
            </div>
        </div>

My JavaScript

.controller('Dashboard', function ($scope, $http, $timeout) {

    $scope.campaigns =[];
    $scope.preview = '';
    $scope.slots = [];
    $scope.maxSlots = 5; // this dynamic

    $scope.safeApply = function(fn) {
        if (this.$root) {
            var phase = this.$root.$$phase;
            if (phase == '$apply' || phase == '$digest') {
                if (fn && (typeof(fn) === 'function')) {
                    fn();
                }
            } else {
                this.$apply(fn);
            }
        } else {
            fn();
        }
    };

    $scope.debug = function(){
        console.log('this is debug');
        console.log($scope.slots.length);
    };

    $scope.uploadImage = function () {
        // console.log('we are here');
        input = document.getElementById('fileinput');
        file = input.files[0];
        size = file.size;
        if (size < 650000) {
            var fr = new FileReader;
            fr.onload = function (e) {
                var img = new Image;

                img.onload = function () {
                    var width = img.width;
                    var height = img.height;
                    if (width == 1920 && height == 1080) {
                        $scope.preview = e.target.result;
                        $scope.perfect = "you added a image";
                        $scope.$apply();

                    } else {
                        $scope.notPerfect = "incorrect definitions";
                        $scope.$apply();
                    }
                };
                img.src = fr.result;
            };

            fr.readAsDataURL(file);
        } else {
            $scope.notPerfect = "to big";
        }
    };

    $scope.addImage = function () {
        if ($scope.slots.length < $scope.maxSlots) {
            $scope.slots.push({
                "slot_id": $scope.slots.length + 1,
                "base_image": $scope.preview,
                "path_image": ""
            });
            $scope.safeApply

        } else {
            window.alert("you have to delete a slot to generate a new one");
            // console.log('you have to delete a slot to generate a new one')
        }
    };

    $scope.SaveImage = function () {
        $http({
            url: "http://www.ccuktech.co.uk/ccuploader/campaigns/updateSlots",
            method: "POST",
            data: { 'campaign': "ben", 'slots': $scope.slots },
            headers: {'Content-Type': 'application/json'}
        }).then(function (response) {
            // success
            console.log('success');
            console.log("then : " + JSON.stringify(response));
            // location.href = '/cms/index.html';
        }, function (response) { // optional
            // failed
            console.log('failed');
            console.log(JSON.stringify(response));
        });
    };

    $scope.removeImage = function(s) {
        $scope.slots.splice($scope.slots.indexOf(s), 1);
    };

    $scope.GetData = function () {
        $http({
            url: "http://www.ccuktech.co.uk/ccuploader/campaigns/getCampaign",
            method: "POST",
            date: {},
            headers: {'Content-Type': 'application/json'}
        }).then(function (response) {
            // success
            console.log('you have received the data ');
            console.log(response);

            $scope.campaigns = response.data;
            //$scope.slots = data.data[0].slots;

        }, function (response) {
            // failed
            console.log('failed getting campaigns goo back to log in page.');
            console.log(response);
        });
    };

    $scope.GetData();
})

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/angular-crud-to-and-from-api/
via @lzomedia #developer #freelance #web

Send form data using AngulaJS not working

I want to insert user data into databse but I can’t send from data through
angularjs and i am new to angular. I check by print_r($_POST) in insert.php but it displays as empty array.How can i send form data using php .please help me

HTML

  <form name="form" ng-submit="signup()">
    <div class="form-group">
      <label for="Name">Name</label>
      <input type="text" class="form-control" placeholder="Enter your  name" name="name" ng-pattern="/^[a-zA-Z]*$/" required ng-model="user.name">
      <span ng-show="form.name.$dirty && form.name.$error.required">Enter  your name</span>
      <span ng-show="form.name.$dirty && form.name.$error.pattern">Name in  characters only</span>
    </div>

    <div class="form-group">
      <label for="Mobile">Mobile Number</label>
      <input type="text" class="form-control" placeholder="Enter your mobile number" name="mobile" required ng-minlength="10" ng-maxlength="10" ng-model="user.mobile">
      <span ng-show="form.mobile.$dirty &&  form.mobile.$error.required">Enter your mobile number</span>
      <span ng-show="form.mobile.$dirty && (form.mobile.$error.minlength || form.mobile.$error.maxlength)">Mobile number should be 10 digits</span>
    </div>

    <div class="form-group">
      <label for="Name">Email</label>
      <input type="email" class="form-control" placeholder="Enter your email" name="email" required ng-model="user.email">
      <span ng-show="form.email.$dirty && form.email.$error.required">Enter your email</span>
      <span ng-show="form.email.$dirty && form.email.$error.email">Enter a valid email</span>
    </div>

    <div class="form-group">
      <label for="pwd">Password</label>
      <input type="password" class="form-control" placeholder="Enter password" name="password" required ng-minlength="8" ng-model="user.password">
      <span ng-show="form.password.$dirty && form.password.$error.required">Enter your password</span>
      <span ng-show="form.password.$dirty && form.password.$error.minlength">Password should be 8 characters</span>
    </div>
      <button class="btn btn-primary btn-block" name="login" id="login_btn" ng-disabled="form.$invalid">Sign up</button>
  </form><br><br>
  <p class="text-center" id="new"><span>Already have an account</span></p>
  <a href="login.php" class="btn btn-default btn-block">Signin</a>
</div>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1  /jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

JS

        var app = angular.module('MyApp', []);
        app.controller('MyCtrl', function($scope, $http) {
            $scope.signup = function(){    
                var data = $scope.user; 

                $http.post("insert.php", data).then(function(resp){

                    console.log(resp);

                });        
            }
        });

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/send-form-data-using-angulajs-not-working/
via @lzomedia #developer #freelance #web

Show pdf and docx in html using angularjs and AWS S3

I’m working with AngularJS and AWS S3 and I’m trying to view the files(.pdf, .docx, .ppt, etc..) in the browser but I’m stuck.

I’m trying to use the google docs view:

<iframe src="http://docs.google.com/gview?url=MY_AWS_S3_URL&embedded=true"></iframe>

But I’m getting this error in console’s browser and obviously the view of this doc is not working.

Anyone know what is happening? Could be a S3 permissions error or maybe its because angularjs doesn’t support it?

EDIT:
I’ve tried this to show .pdf files and it works but just for .pdf files.

<object width="400" height="500" type="application/pdf" data="your_url" id="pdf_content">
  <p>ERROR!!</p>
</object>

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/show-pdf-and-docx-in-html-using-angularjs-and-aws-s3/
via @lzomedia #developer #freelance #web

Where to place jQuery plugins in AngularJS [duplicate]

This question already has an answer here:

I am a beginner to AngularJS. I need to know what’s the best practice to store jQuery plugins in the project folder. I have seen strong opposition to placing them in node_modules folder.

Please tell me where and how I can include such plugins? I know about directives, just need to know how to include them in path.

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/where-to-place-jquery-plugins-in-angularjs-duplicate/
via @lzomedia #developer #freelance #web

DatePicker being truncated in dataTable

I have several datePicker in a dataTable , and a vertical scroll on that table.
The issue is that when i open my datepicker, it doesn’t “pop outside” the datatable, but does something like this:

enter image description here

Looking online i found that the solution could be to use the position:relative style on the parent of the datePicker , as stated on the Git page of the datepicker , but it does not seem to work on my case.

Here the directive I use to modify the datepicker :

var parent = $(elem).parent();
parent.css('position', 'relative');
var dtp = parent.datetimepicker({
     format: "DD-MM-YYYY HH:mm:ss",
      showTodayButton: false,
});

Any hint? Did i got something wrong?

EDIT
Here is the HTML of the datatable

<div class="table-responsive" >
            <table id="newFornitures" class="table" datatable="ng" dt-options="dtOptions">
                <thead>
                    <tr>
                        <th class="col-order">START_DATE</th>
                        <th class="col-order">END_DATE</th>
                    </tr>
                </thead>
                <tbody > 
                    <tr ng-repeat="row in insSupplies">
                        <td>
                            <div class="input-group date">
                                <input type="text" class="form-control" value="insSupplies[$index].start_date" ng-model="insSupplies[$index].start_date" dateDirective>
                                <span class="input-group-addon">
                                    <span class="e-ico">today</span>
                                </span>                                     
                            </div>
                        </td>
                        <td>
                            <div class="input-group date">
                                <input type="text" class="form-control" value="insSupplies[$index].start_date"  ng-model="insSupplies[$index].end_date" dateDirective>
                                <span class="input-group-addon">
                                    <span class="e-ico">today</span>
                                </span>                                     
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

and here are the options of the dataTable :

$scope.dtOptions = DTOptionsBuilder.newOptions()
            .withDisplayLength(10)
            .withOption('bFilter', false)
            .withOption('bProcessing', false)
            .withOption('sScrollY', "250px")
            .withOption('sScrollX', false)
            .withLanguage({ "sEmptyTable": "Nessuna fornitura presente","sInfoEmpty" : ""})
            .withOption('bPaginate', false);

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/09/27/datepicker-being-truncated-in-datatable/
via @lzomedia #developer #freelance #web