AngularJS

382

Solutions

260

Contributors

AngularJS is an open-source web application framework used to develop single-page applications. It aims to simplify both the development and the testing of such applications by providing a framework for client-side model–view–controller (MVC) and model–view–viewmodel (MVVM) architectures, along with components commonly used in rich Internet applications. AngularJS is the frontend part of the MEAN stack, together with Node.js runtime, Express.js backend framework and MongoDB database.

Share tech news, updates, or what's on your mind.

Sign up to Post

I have the following AngularJs code:
var myApp = angular.module('myApp', []);

myApp.controller('mainController', ['$scope', '$http', function ($scope, $http) {
    
    
    $http.post('/Home/GetDesiredResult', { numberOfRecords: 20 })
        .then(function (response) {
            // success
            console.log(response);
            $scope.desiredResult = response.data;    

             // Over here, $scope.desiredResult contains data       
        }, 
            // Error
            function (response) {
                console.log(response);
        });

    // Over here, $scope.desiredResult is undefined


}]);

Open in new window


What is the cleanest way to get the data I get back from my $http.post saved in $scope.desiredResult so it is accessible in my app?
0
Optimize your web performance
LVL 1
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Hello I am using Angular UI Grid to display the data in neat and clean manner. In the UI grid, there is one column as "Duration". I want to sort this column in descending order but unfortunately, i am unable to do that. I tried but it is sorting in text format.
In the controller part I have written as follows:
$scope.sortTrendingEvents = function () {
$scope.slaGridOptions.data = $filter('orderBy')($scope.slaGridOptions.data, "duration", true)
console.log('this button is clicked when trending event is pressed');
};
In the HTML part I have written as:
<button id="toggleFiltering" class="nxn-btn-primary nxn-mar-right-10" ng-click="sortTrendingEvents()">Trending Events</button>

Trending Events
In short what I have done is on the click of a button the Duration column must be sorted in DESC order but with the help of this code,

I am unable to sort this column in number pattern.
Please do guide me. Thank you so much.
0
I am following the tutorial from here: "http://itsolutionstuff.com/post/codeigniter-3-and-angularjs-crud-with-search-and-pagination-exampleexample.html"

I am getting these errors: errors
Where am i going wrong ? i have tried exhaustively to search for answer or hint but i am lost, i am obviously pretty new to codeigniter.
Here is link to github files that i downloaded for tutorial. I appreciate any help or suggestion. Thank You all.
0
I am learning Angular, Node, npm, deployd, mongodb, etc.  I am making my way through a book titled "Pro AngularJS" by Adam Freeman.

on page 120 I am attempting to prepare the data for a "real world" application called "sportsstore".

I was instructed to install a module called "deployd" which apparently is used for modelling  API's for web applications.

I did that and when I try to start start the "deployd" service I get an error:

C:\PROGRA~2\deployd>dpd -p 5500 sportsstore\app.dpd --mongod
starting deployd v0.8.9...
internal/child_process.js:289
  var err = this._handle.spawn(options);
                         ^

TypeError: Bad argument
    at TypeError (native)
    at ChildProcess.spawn (internal/child_process.js:289:26)
    at exports.spawn (child_process.js:380:9)
    at Object.exports.restart (C:\Users\knowlton\AppData\Roaming\npm\node_modules\deployd\lib\util\mongod.js:38:14)
    at Command.start (C:\Users\knowlton\AppData\Roaming\npm\node_modules\deployd\bin\dpd:149:16)
    at Command.listener (C:\Users\knowlton\AppData\Roaming\npm\node_modules\deployd\node_modules\commander\index.js:301:8)
    at emitOne (events.js:96:13)
    at Command.emit (events.js:188:7)
    at Command.parseArgs (C:\Users\knowlton\AppData\Roaming\npm\node_modules\deployd\node_modules\commander\index.js:617:12)
    at Command.parse (C:\Users\knowlton\AppData\Roaming\npm\node_modules\deployd\node_modules\commander\index.js:458:21)
    at Object.<anonymous> 

Open in new window

0
I am exporting a table using pdfmake
The table exports, but there is one item that is 'undefined'.  

I have a main page with multiple tabs and once you hit the 'Printer Friendly' btn, a pdf report opens in a new tab for the specific tab you selected.  The 'printer friendly' btn is what exports the page.  

This code broadcasts  the print function to produce the pdf report depending on what tab you are on.
$scope.printDiv = function(divName) {		
		$rootScope.$broadcast('print');		
	}
	

Open in new window


and the button
<button ng-click="printDiv('rollup-tab')">Printer Friendly</button>

Open in new window



Here is the rest of the code.

Table creation and exports the pdf pdf
$scope.$on('print', function(event, filter) {
			var docDefinition = {

					content: [	
					          {
						  table: {

					              body: [                   			                
					                [ 
					                  '',
					                  'Actual Pieces Issued',
					                  {text: $filter('mcGoalNumberFilter')($scope.actualPiecesMCGoal) + ' /wk'},			                  
					                  {text: $scope.actualPiecesMon, style: 'tableData'},
					                  {text: $scope.actualPiecesTues, style: 'tableData'},
					                  {text: $scope.actualPiecesWed, style: 'tableData'},
					                  {text: $scope.actualPiecesThurs, style: 'tableData'},
					                  {text: $scope.actualPiecesFri, style: 

Open in new window

0
<div class="input-controls">
     <div>
       <label>
        <input #female name="gender" type="radio" value="Female" (click)="gender=female.value"/>
        </label>
       </div>
      </div>

import {Component} from '@angular/core';
@Component({
    selector: 'input-controls',
    templateUrl: './components/input-controls/input-controls.html'
})
export class InputControls {
    gender:string;
}
0
I am using iFrame in my application's html, with ng-src="https://someOtherServer.co,/portal?token=theTokenID&language=en&embedded=true"
This iframe is not loading on IE bubt works in Chrome.

I have already tried adding:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
New Jquery library
but getting nowhere.

ANy help appreciated.

Thanks
0
I have two sharepoint lists that are identical structurally (only difference is data) now I want to be able to query both list and consolidated the returned values.
Very new at javascrit and Angular but I've attempted to just duplicate my first query and I seem to be getting output from both lists but cannot figure out how to consolidate into one.

see code below.

(function () {
  'use strict';

  angular
    .module('myApp.core')
    .controller('DefaultController', DefaultController);

  DefaultController.$inject = ["SharePointService"];

  function DefaultController(SharePointService) {

    var vm = this;






    vm.search = function () {


        SharePointService.getWithFilter('ExpectationsList1', "?$select=Id,DocTitle,ParaNum,SentText&$filter=substringof('" + vm.query + "', SentText) eq true").then(function (response1) {
 
                //vm.expectations = response1

                console.log(response1);

        });
        SharePointService.getWithFilter('ExpectationsList2', "?$select=Id,DocTitle,ParaNum,SentText&$filter=substringof('" + vm.query + "', SentText) eq true").then(function (response2) {

            //vm.expectations = response2


			console.log(response2)			

        });


        

    }


  }

})();

Open in new window

0
I have two distinct modules in an Angular app, a parent and a child. They both also have distinct default routing HTML pages. The Parent router has one basic router-outlet setup. However for the Child default route, I have a bootstrap side menu and another router-outlet.

When I go to the Child Module section, the side menu is appearing, however it looks like the Parent router-outlet is being utilized. I've searched for several hours for a resolution to this issue, but cannot find one. Each module (Parent and Child) has their own routing files and modules. And each module file has a distinct reference to a specific HTML initial routing page.

I'm sure this is something simple and stupid (which these things usually are), but any help would be appreciated. The angular.io documentation is so bad that finding anything that falls outside the realm of the 'Hero' demo is a waste of time.

Thanks!
0
I am populating a table by adding first column as radio button. Want to select first row radio button as default and fire the radio button event ng-click.

            
<div class="col-5-md col-lg-8">
            <div class="well well-sm">
                <table id="eventsTable" st-safe-src="vm.AllEmployees" st-table="displayCollection" class="table table-striped">
                    <thead>
                        <tr>
                            <th> </th>
							<th st-sort="EMPLOYEE_ID">EMPLOYEE ID</th>
                            <th st-sort="EMPLOYEE_NAME">EMPLOYEE NAME</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr st-select-row="row" ng-repeat="row in displayCollection">
                            <td><input type="radio" value="false" name="eventsRadio" ng-click="vm.onEventSelection(row)" /></td>
                            <td>{{::row.EMPLOYEE_ID}}</td>
                            <td>{{::row.EMPLOYEE_NAME}}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

Open in new window


Thanks for your help in advance.
0
Monthly Recap
Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

calling above using in Angular as:

 function Login(email, password, callback)  
 {  
        var GetAll = new Object();  
        GetAll.email = email;   
        GetAll.password = email;  
        $http({  
            url: "http://localhost:52587/api/TokenAuth/Login",  
            dataType: 'json',  
            method: 'post',  
            data: JSON.stringify(GetAll),       
            headers: {
                      'Content-Type': 'application/json'
                      }      
         }) 
      .then(function loginSuccessCallback(response)
 {...

Open in new window

I've tested this using swagger and ajax which worked fine. I set it up with json object in the body (set to raw and JSON (application/json)).

I have written the following Web API:

namespace WEBAPI.Controllers  
{   
    public class user  
    {   
        public string email { get; set; }   
        public string password { get; set; }  
    }

 [Produces("application/json")]   
 [Route("api/[controller]")]       
 public class TokenAuthController : Controller    
 {

  [HttpPost("Login")]    
  public async Task`<IActionResult>` Login([FromBody]user usr)   
{   
..................               
..................             
}      
}         
}

Open in new window

But I am getting [FromBody ] 415 unsupported media type. Please help me.
Anyone see where I'm going wrong?
0
We have a web page built using angularJS where we are showing the videos of the uploaded videos using JWPlayer,

but When the web page is loaded, the JWPlayer doesn't load the video instead it shows half the width of the actual video width and when the play button is clicked, video is not played instead video starts to download.

This behavior is seen across different browsers, across different systems. However, on certain systems it is playing fine. Also, on certain systems it is playing fine in Chrome but not playing on firefox. The browser setting across the browsers on different systems is the same.

When the element is inspected, different HTML tag is shown for browsers where it is not working and a different HTML is shown for browser where it is working.

For half width player (not working): The 'a' tag is shown with the with href path where the content gets downloaded when clicked on play.(half-image.png)
For full width player (working): The video is wrapped in div container with default player embedded in it and content is played when clicked on play.(full-image.jpg)

After updating the browser and re-logging in, the JWPlayer loads the video with full width in some cases.

versions used:
jwplayer : 0.2.1
ng-jwplayer : 5.9.2118
half-image.png
full-image.jpg
0
I am exporting a table as a pdf using the pdfmake library.  (http://pdfmake.org/#/gettingstarted)
This is accomplished correctly when I select one specific route and one table is successfully exported.  However, when I select 'All' within the Route filter, multiple tables appear in the main page and I want to export all those tables as one pdf when a user selects 'Route: All'.

I have several tabs created for my page each of which contains their own table data.  

There is a print btn in the html, which also contains the creation of the tabs as well as the btn
<button ng-click="printDiv('rollup-tab')">Printer Friendly</button>

Open in new window


Within the js, this broadcasts to the tab you are currently on and is called
$scope.printDiv = function(divName) {
		//BROADCAST TO EACH TAB
		$rootScope.$broadcast('print');	
		
	}

Open in new window


Within the lcp.js file (lcp tab), it makes a call to the broadcast, which exports the table as a pdf.
$scope.$on('print', function(event, filter) {

			var docDefinition = {
					info: {
					    title: 'LCP'
					    
					  },
					content: [
					          
							{
							    margin: [0, -40, 0, 30],	 	
								image: 'data:image/png;base64,iVBORw0KGgo......'
								width: 200,
								height: 58,
								style: 'centerImage',

							  },					  
					         
					         {
						        	  fontSize: 9,
								       margin: [0,-30, 0, 10],
								       
									  table: {
										  headerRows: 1,
										  

Open in new window

0
After upgrading to node.js 7.5.0, I encountered this error too:  Loading "grunt-karma.js" tasks...ERROR >> TypeError: Cannot read property 'prototype' of undefined
0
how to send the combined parameters of both sorting and paging to add back end query
0
Dear experts here, I am learning angular 2 these days. When I tied to run "npm install" on an angular 2 application for displaying a slider document, it threw me into an error about python. I have two versions of python installed, how could I set up %PYTHON% PARAMETER?

THANKS.


C:\angular-training-slides\slides\node_modules\bufferutil>if not defined npm_config_node_gyp (node "C:\Users\jyu\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild )  else (node "" rebuild )
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "C:UsersjyuAppDataLocalProgramsPythonPython35python.EXE", you can set the PYTHON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (C:\Users\jyu\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\configure.js:454:19)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Users\jyu\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\configure.js:480:16)
gyp ERR! stack     at C:\Users\jyu\AppData\Roaming\npm\node_modules\npm\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:114:15)
gyp ERR! System Windows_NT 6.1.7601
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\jyu\\AppData\\Roaming\\npm\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\angular-training-slides\slides\node_modules\bufferutil
gyp ERR! node -v v7.7.4
gyp ERR! node-gyp -v 

Open in new window

0
I want to use D3 and dagre-d3 libraries in my Angular2 project. The project has been created using Angular2 CLI.

To integrate D3 with Angular2, I did the following from command prompt -

npm install d3 --save
npm install @types/d3 --save-dev

Open in new window


then in my component

import * as d3 from 'd3';
 ngOnInit() {
    d3.select("body").append("span")
      .text("Hello world!");
  

Open in new window


this displayed the "Hello world!" text on the page, so that means d3 is correctly configured.

Now, in order to configure dagre-d3 [https://github.com/cpettitt/dagre-d3/wiki#npm-install], I did the following

npm install dagre-d3 --save

Open in new window


in angular-cli.json, I added dagre-d3 reference in the scripts array


 
"scripts": [
        "../node_modules/jquery/dist/jquery.min.js",
        "../node_modules/bootstrap/dist/js/bootstrap.min.js",
        "../node_modules/dagre-d3/dist/dagre-d3.js"

      ],

Open in new window


then I installed dagre-d3 types

npm install @types/dagre-d3 --save

Open in new window


Now in the Angular2 component, I have done the following to test the integration with dagre-d3


import * as d3 from 'd3';
import * as dagreD3 from 'dagre-d3';

ngOnInit() {
    d3.select("body").append("span")
      .text("Hello, world!");

    var g = new dagreD3.graphlib.Graph();  
}

Open in new window


This gives me an error in Browser console

Console error
how can I have dagre-d3 work with angular2? Am I missing a step?
0
HI

I want to calculate distance is within the range of 1.0 km.
Iam using google distanematrix to get the distance in km to the place, and its working fine.

function returns a string, witch looks like f.eks:
- "0.9 km"
- "6.9 km"

I want to calculate so that distance is within the range of 1.0 km and not higher, but lower is ok...
But some times i also get distance in meter when iam close to the place, f.eks:
"14 m"
"20 m"

So how can i calculate correct distance if i get distance in double string value or as an int value?

Here is my if statement where iam checking the returned distance in km is lower then "1.0 km"
var dist = str.split(" "); //Split so i can only get the value and not the string "km"
if (Math.round(dist[0] * 100) <= Math.round('1.0' * 100)) {
                         alert('you are in the range')
                        }
else{
alert('you are to far away')
}

Open in new window





iam not getting the correct result with the code above, any suggestion for how i can calculate the correct way will be really appriciated...

Thanks in advance
0
add.js

var fs = require('fs');
var addData = " <book category='children'><title>Harry Potter</title><author>J K. Rowling</author><year>2005</year><price>29.99</price></book>";
var cursor = "//cursor";
addData += cursor;
//var ws = fs.createWriteStream('./new_xml.xml');           //creating new file in same folder.      
fs.exists("new_xml.xml", function (exists) {
    if (exists) {
        //Adding new node in existing xml file      
        fs.readFile("new_xml.xml", "utf-8", function (err, data) {
            if (err) {
                console.log(err);
                return;
            }
            var newData = data.replace(/\/\/cursor/, addData);
            fs.writeFile("new_xml.xml", newData, function (err) {
                if (err) {
                    console.log(err);
                    return;
                }
                console.log("XML node is added successfully........");
            });
            // console.log(data);      
        });
    } else {
        console.log("File not exists.................");
    }
});


new_xml.xml

<bookstore>
   <book category="cooking">
       <title lang="en">Everyday Italian</title>
       <author>Giada De Laurentiis</author>
       <year>2005</year>
       <price>30.00</price> </book>
   //cursor
</bookstore>



In this example before //cursor 1 book node is added after executing add.js.......in node js.....(using this command node add.js).

.
.
BUT
same code executed in …
0
Linux Academy Android App Now Supports Chromecast
Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

hai,
I using angularjs for modal draggable,
If am drag the modal automatically it will lock the header with a certain limit..there after not able to drag again..


.provider('moveableModal', ['$provide', function ($provide) {

            var moveableModal = {
            options: {
                elSelector: '',
                targetSelector: ''
            },
            $get: function () {
                var startX = 0;
                var startY = 0;
                var x = 0;
                var y = 0;


                if (!moveableModal.options.elSelector && !moveableModal.options.targetSelector) {
                    return;
                }

                var $document = angular.element(document);
                var element = angular.element(moveableModal.options.elSelector);
                var target = angular.element(moveableModal.options.targetSelector);


                    function mousemove(event) {
                    y = event.pageY - startY;
                    x = event.pageX - startX;
                    target.css({
                        top: y + 'px',
                        left: x + 'px'
                    });
                }

                 function mouseup() {
                    $document.unbind('mousemove', mousemove);
                    $document.unbind('mouseup', mouseup);
                }
                $('#drag').draggable({
                    containment: 'parent'

                });


                

Open in new window

0
i am not able to use $http post method in angularjs
0
we have a Geo location issue. In our angularjs application we are using Geo location   which find the current position of the place. is there is any issue with the code below

error it gives

   
 getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.

Open in new window


Code is below

In Component:
/*---- geo code start ----*/
   
 public loginUrl = 'http://ws.geonames.org/countryCodeJSON?';
    lat: any;
    lng: any;
    verify: boolean=false;
    location = {};
    geoDetails = new GeoCounty();
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(this.setPosition.bind(this));
        }

setPosition(position) {
        this.location = position.coords;
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.loginUrl = this.loginUrl + 'lat=' + this.lat + '&lng=' + this.lng + '&username=demo';
        console.log(this.loginUrl);
        this.getGeodata();
    }
    getGeodata() {
        this.verify=true;
        this.geoService.getGeoData(this.loginUrl)
            .subscribe(
            geoDetails => {
                if (geoDetails.countryCode == undefined || geoDetails.countryCode == '') {
                    geoDetails.countryCode = this.defcountrycode;
                }
                this.getCountryLanguages(geoDetails.countryCode);
                this.geoDetails = geoDetails;
                alert(geoDetails.countryCode);
            },
            error =>{ this.errorMessage = <any>error; alert(this.errorMessage);});
    }

Open in new window


    /*---- geo code end ----*/


In Service:
 
getGeoData(url): Observable<GeoCounty> {
    return this.http.get(url)
      .map(this.extractData)
      .catch(this.handleError);
  }

  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }

Open in new window

0
I have a expressions that will not show if $http is called:

Controller
function StaysCtrl($scope, $http, $state, Idle, notify, AuthSrv, appResource) {

    // Will not show up if I make a $http call
    this.helloText = 'Welcome to Stays';

    //appResource.query(function (data) {
    //    $scope.stays = data;
    //});

    // If I comment out this $http call the helloText will show up.
    $http({
        method: 'GET',
        dataType: 'json',
        headers: {
            "Content-Type": "application/json"
        },
        url: 'http://localhost:6060/api/stay/10/desc',
        data: JSON.stringify(),
    }).success(function (data) {
        $scope.stays = data;
    });
    
}

Open in new window


HTML
<div ng-controller="StaysCtrl as stays" class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="text-center m-t-lg">
                <h1>
                    {{stays.helloText}}
                </h1>
                <small>Configure in config.js as minor state.</small>
            </div>
        </div>
    </div>

    <div ng-repeat="stay in stays">
        <div>{{stay.stayID}}</div>
    </div>
</div>

Open in new window


What am I missing?
0
Hi there,
I need to change the  extra-settings  in the ng-dropdown-multiselect directive dynamically. Depending on the number of items selected I need to either show the Uncheck All button or don't show. I changed the settings,  but it does not seem like the directive can pick up the changes dynamically. Is there any way to achieve it?
0
function finalizeVideo() {                            
                            var start_time = +new Date;
                            video.compile(false, function (output) {
                                var end_time = +new Date;

                                var video_url = webkitURL.createObjectURL(output);              //console.log(video_url);                                

                                document.getElementById('awesome').src = video_url; //toString converts it to a URL via Object URLs, falling back to DataURL
                                var url = document.getElementById('awesome').src;
                                document.getElementById('download').style.display = '';
                                document.getElementById('download').href = video_url;
                                document.getElementById('status').innerHTML = "Compiled Video in" + (end_time - start_time) + "ms, file size: " + Math.ceil(output.size / 1024) + "KB";

                                $scope.user = function () {
                                    // Note that newName can be undefined for two reasons:
                                    // 1. Because it is called as a getter and thus called with no arguments
                                    // 2. Because the property should actually be set to undefined. This happens e.g. if the
                                    // input is invalid
                                    var newName;…
0

AngularJS

382

Solutions

260

Contributors

AngularJS is an open-source web application framework used to develop single-page applications. It aims to simplify both the development and the testing of such applications by providing a framework for client-side model–view–controller (MVC) and model–view–viewmodel (MVVM) architectures, along with components commonly used in rich Internet applications. AngularJS is the frontend part of the MEAN stack, together with Node.js runtime, Express.js backend framework and MongoDB database.