pass data between components with $scope.$emit()

I’m trying to pass data between two components that have the same parent component (simple version: I have child1 component, child2 component, and both of them are children of parent component). Also all the components are as controllers.

Parent component is also a root component (it doesnt have any parent components) so I thought I had to use $rootScope?

If i want to pass a var myVar (integer) from child1 to child2 I guess I should do :

in child1 component:

$rootScope.$emit('myEvent', vm.myVar);

in parent component:

$scope.$on('changeTab', function(){
   console.log('parent', vm.myVar);
});
$scope.$broadcast('changeTab', vm.myVar);

in child2 component:

$rootScope.$on('changeTab', function () {
    console.log('child2', vm.myVar);
});

I am new to this and don’t understand why this doesn’t work, probably nothing big, if anyone could help me out would appreciate it 🙂 ty !

By the way I get “undefined” in both console logs, but well myVar is defined properly in child1.

Trigger keydown on text-input with jQuery, retain value after event

Using Tampermonkey on an angularjs site.
I’m prepopulating an inputbox with a value whenever I open the url, but the search is triggered by typing. So I need a keydown-event ie “space” to trigger the search.

I’ve figured out how to trigger a keydown-event, but it overrides the value already in the inputbox.
How do I retain it, while still triggering a keydown?

(function() {
'use strict';

var herId = getParameterByName('Q');
window.setTimeout(function() {
    var el = document.querySelector('.form-control');
    el.value = herId;
}, 200);

window.setTimeout(function() {
    var e = jQuery.Event("keydown");
    e.which = 32; // # Some key code value
    $("input").val(String.fromCharCode(e.which));
    $("input").trigger(e);
}, 1600);
})();

function getParameterByName(name, url) {
   if (!url) url = window.location.href;
   name = name.replace(/[\[\]]/g, "\\$&");
   var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
   results = regex.exec(url);
   if (!results) return null;
   if (!results[2]) return '';
   return decodeURIComponent(results[2].replace(/\+/g, " "));
}

I’m using the delays because the page takes some time to load.

multiple select is not working :angularjs

I’m trying to select multiple value at a time using ui-select2 and for this i have added some angular-js script like

    <link rel="stylesheet" href="<?php echo base_url(); ?>angular-js/bower_components/select2/select2.css">
    <script type="text/javascript" src="<?= base_url() ?>angular-js/bower_components/jquery/jquery.js"></script>
    <script type="text/javascript" src="<?= base_url() ?>angular-js/bower_components/select2/select2.js"></script>
    <script type="text/javascript" src="<?= base_url() ?>angular-js/bower_components/angular/angular.js"></script>
    <script type="text/javascript" src="<?= base_url() ?>angular-js/bower_components/angular-ui-select2/src/select2.js"></script>

and html code

<select multiple="multiple" ui-select2 ng-model="submitAdsFormData.city_id" ng-init="get_city_by_search()"  style="width:300px" required>
<option value="{{x.name}}" ng-repeat ="x in searchResult">{{x.name}}</option>
</select>

For example, i want this type of select
https://jsfiddle.net/NathanFriend/rLmztr2d/ but in angularjs.

But not getting selected multiple value.can anyone help me to get this.
Thanks in advance.

How to Pass Data in Angularjs

firstapp

 var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
    $scope.myWelcome = response.data;
});
});

sencond app

 var app = angular.module('myApp2', []);
app.controller('myCtrl2', function($scope, $http) {
$http.get("fsd.htm").then(function (response) {
    $scope.myWelcome = response.data;
});
});

How to Pass data from one app to another app in angularjs ?

I want to print the whole result coming from the server – AngularJs

I’m new to angularJs. I’m doing a university project with spring boot and angularJs.

I want to print all the result coming from the server.

here is my codes.

app.js

'use strict';

    var App = angular.module('myApp',[]);

HomeController.js

 'use strict';


App.controller('HomeController', ['$scope', 'HomeService', function($scope, HomeService) {


$scope.getDeviceList = function () {
        HomeService.getDeviceList()
          .then (function success(response){ 
              $scope.details = responce.data;
              $scope.errorMessage = '';
          },
          function error(response){
              $scope.errorMessage = 'Error occured!!!';
              $scope.message = response.data.message;
        });
    }

}]);

HomeService.js

'use strict';

App.service('HomeService', ['$http', '$q', function($http, $q){


var REST_SERVICE_URI = '/customer';




this.getDeviceList = function getDeviceList(){
    return $http.get(REST_SERVICE_URI + '/get_device_list')

}

}]);

home.html

 <!DOCTYPE html>
<html ng-app="myApp">

    <head>
        <title>Welcome to Ncheck Surveilance</title>

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular-route.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular-resource.js"></script>


        <script type="text/javascript" src="../js/app.js"></script>
        <script type="text/javascript" src="../controller/RegistrationController.js"></script>
        <script type="text/javascript" src="../controller/HomeController.js"></script>
        <script type="text/javascript" src="../service/RegistrationService.js"></script>
        <script type="text/javascript" src="../service/HomeService.js"></script>

      </head>

</html>   
<body ng-controller="HomeController">

    Logged in user: <b th:inline="text"> [[${#httpServletRequest.remoteUser}]] </b>
    <br>
    <span class="panel-title">Registered Devices</span>
     <span>
            <button id="button" name="button" class="btn btn-primary"   ng-click="getDeviceList()" >Show</button>
                 {{details}}
            {{error}}
    </span>
   <div>
        Hello : <b th:inline="text">  </b>
        <form th:action="@{/logout}" method="POST">
            <input type="submit" value="Logout"/>
       </form>
   </div> <br/>  
</body>

My problem is when I click “Show” button I get a error (Possibly unhandled rejection: {}) in the web browser console.

how to unit test an angular controller using jasmine that makes call to a service/factory and sets data fafter receiving response from factory/service

I’m learning unit testing on angularjs application using Jasmine and Kama.

I have a method in an angular controller which calls a method in a factory, after data is received from factory, I set a variable in .then() block
I need to test if response data from angular factory was assigned to variable or not after getting response.

Here is the controller making call to factory

$scope.getSupportedWebsites = function() {
$scope.searchHostsFound = true;

    baseFactory.getWebsites().then(function(response) {
        cfpLoadingBar.complete();
        $scope.hostsFound = false;
        if (response.data.length > 0) {
            $scope.hostsFound = true;
        }

        $scope.supportedWebsites = response.data;
        for (var key in response.data) {
            (function() {}(key, response));
        }

    }, function(error) {
        cfpLoadingBar.complete();
        $scope.notify(error.data.message, 'danger');
    });

};
$scope.getSupportedWebsites();

and jasmine code that I've written so far to test this  method is this:


beforeEach( angular.mock.module( 'myApp' ) );
describe( 'Home Controller', function () {
    var $controller, baseFactory, homeController, $scope, $q, deferred, $rootScope;
    var $httpBackend;

    beforeEach( inject( function (_$controller_, $rootScope, _$q_,
        _$httpBackend_, _baseFactory_, _$rootScope_) {
        $q = _$q_;
        $httpBackend = _$httpBackend_;
        baseFactory = _baseFactory_;
        $rootScope = _$rootScope_;
        deferred = _$q_.defer();
        $controller = _$controller_;
        $scope = $rootScope.$new();
        deferred.resolve( {data: 'somevalue'} );
        homeController = $controller( 'homeController', { $scope: $scope,
            baseFactory: _baseFactory_ } );



    } ) );
    it( 'should be defined', function () {
        expect( homeController ).toBeDefined();
    } );
    it( 'get supported websites method should be defined', function () {
        expect( $scope.getSupportedWebsites ).toBeDefined();
    } );


    it( 'get supported websites should work', function () {

spyOn(baseFactory, 'getWebsites').and.returnValue(deferred.promise);


    } );

    it('supported Websites should be set',function(){
        $scope.getSupportedWebsites();

        expect(baseFactory.getWebsites).toHaveBeenCalled();
        expect($scope.supportedWebsites).toBeDefined();

// I need to test if the variable above was set or not after getting response from factory.
})
} );
How to test this ?

AngularJS broadcast event is not listening inside directive

I’m trying to export some data to xls, pdf, get a example on by using AngularJS $broadcast events – plunker.

This is my controller:

admin.controller('ctrlReuniaoRelatorioDetalhe', ['$scope', '$http', '$controller', '$window', 'baseURL', 'blockUI', function($scope, $http, $controller, $window, baseURL, blockUI) {
  angular.extend(this, $controller('BaseListController', {
    $scope: $scope
  }));

  $scope.Formulario = "ReuniaoRelatorioDetalheViewModelForm";
  $scope.dataemissao = new Date();
  ctrlReuniaoRelatorioDetalhe = $scope;
  ctrlReuniaoRelatorioDetalhe.http = $http;


  $scope.reportData = [{
    "EmployeeID": "1234567",
    "LastName": "Lastname",
    "FirstName": "First name",
    "Salary": 1000
  }, {
    "EmployeeID": "11111111",
    "LastName": "Lastname 1",
    "FirstName": "First name 1",
    "Salary": 2000
  }, {
    "EmployeeID": "222222222",
    "LastName": "Lastname 2",
    "FirstName": "First name 2",
    "Salary": 3000
  }, {
    "EmployeeID": "333333333",
    "LastName": "Lastname 3",
    "FirstName": "First name 3",
    "Salary": 4000
  }];

  $scope.exportAction = function(option) {

    switch (option) {
      case 'pdf':
        $scope.$broadcast('export-pdf', {});
        break;
      case 'excel':
        $scope.$broadcast('export-excel', {});
        break;
      case 'doc':
        $scope.$broadcast('export-doc', {});
        break;
      case 'csv':
        $scope.$broadcast('export-csv', {});
        break;
      default:
        console.log('no event caught');
    }
  }
}]);

This is my directive:

 app.directive('exportTable', function() {
   var link = function($scope, elm, attr) {
     $scope.$on('export-pdf', function(e, d) {
       elm.tableExport({
         type: 'pdf',
         escape: false
       });
     });
     $scope.$on('export-excel', function(e, d) {
       elm.tableExport({
         type: 'excel',
         escape: false
       });
     });
     $scope.$on('export-doc', function(e, d) {
       elm.tableExport({
         type: 'doc',
         escape: false
       });
     });
     $scope.$on('export-csv', function(e, d) {
       elm.tableExport({
         type: 'csv',
         escape: false
       });
     });
   }
   return {
     restrict: 'C',
     link: link
   }
 });

I dont have any idea why $scope.$on() in my directive is not listening to my event. The $scope.exportAction is working but when “broadcast” is fired, nothing happends.

How to pass ng-model as parameter to controller

How can i pass the ng-model with it’s value as a parameter to a function in a controller from html.I tried to pass the ng-model as string to the controller but it didn;t works can anyone tell me how to do it.

Html:

<input stopccp decimalpoint
      ng-model="vm.product.rate"
      placeholder="0"
      type="number"
      ng-change="vm.fillStarted()"
      maxlength="5"
      ng-keydown="vm.checkMaxLength(5, vm.product.rate)"
      ng-click= "vm.hideScrollContent()"/>

Controller:

var vm = this;
function checkMaxLength (maxLength, model) {
  $log.log('checkMaxLength got called', maxLength);
  $log.log('model is', model);
  $log.log('model value', model.value);
  // if (vm.product.rate.length === maxLength) {
  //   vm.product.rate.value = vm.product.rate.value.slice(0, -1);
  // }
}

Logs:

checkMaxLength got called 5
model is 
model value undefined

How to set default value to select when I am using ng-model and and ng-change?

I am asking this question because ng-model overwrites default value in select tag. So I need to set <option value="-translation.published_at" selected>{{ 'Newest first' | translate }}</option> to be a default value. This is my code:

    <div class="filter__order filter--select p-rel">
        <select id="order" class="text-dark-gray" ng-model="sortedBy" ng-change="filterByDate(sortedBy)">
            <option value="-translation.published_at" selected>{{ 'Newest first' | translate }}</option>
            <option value="translation.published_at">{{ 'Oldest first' | translate }}</option>
        </select>
    </div>

Can’t access parent $scope in $mdBottomSheet

I can’t access the parent ä$scope in my $mdBottomSheet. Iwant be able to create this bottom sheet and click one of the buttons inside of it displaying the parent $scope data. I made a codepen.

That’s the code by the way:

<div ng-controller="BottomSheetExample" class="md-padding bottomSheetdemoBasicUsage" ng-cloak="" ng-app="MyApp">

  <div class="bottom-sheet-demo inset" layout="row" layout-sm="column" layout-align="center">

    <md-button flex="50" class="md-primary md-raised" ng-click="showGridBottomSheet()">Show as Grid</md-button>
  </div>

  <div ng-if="alert">
    <br>
    <b layout="row" layout-align="center center" class="md-padding">
      {{alert}}
    </b>
  </div>
<script type="text/ng-template" id="bottom-sheet-grid-template.html"><md-bottom-sheet class="md-grid" layout="column" ng-cloak>
  <div>
    <md-list flex layout="row" layout-align="center center">
      <md-list-item ng-repeat="item in items">
        <div>
        <md-button class="md-grid-item-content" ng-click="listItemClick($index)">
          <md-icon md-svg-src="{{item.icon}}"></md-icon>
          <div class="md-grid-text"> {{ item.name }} </div>
        </md-button>
        </div>
      </md-list-item>
    </md-list>
  </div>
</md-bottom-sheet>
</script>

</div>

JavaScript:

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])
.config(function($mdIconProvider) {
    $mdIconProvider
      .icon('share-arrow', 'img/icons/share-arrow.svg', 24)
      .icon('upload', 'img/icons/upload.svg', 24)
      .icon('copy', 'img/icons/copy.svg', 24)
      .icon('print', 'img/icons/print.svg', 24)
      .icon('hangout', 'img/icons/hangout.svg', 24)
      .icon('mail', 'img/icons/mail.svg', 24)
      .icon('message', 'img/icons/message.svg', 24)
      .icon('copy2', 'img/icons/copy2.svg', 24)
      .icon('facebook', 'img/icons/facebook.svg', 24)
      .icon('twitter', 'img/icons/twitter.svg', 24);
  })
.controller('BottomSheetExample', function($scope, $timeout, $mdBottomSheet, $mdToast) {
  $scope.alert = '';
  $scope.items = [
    { name: 'Hangout', icon: 'hangout' },
    { name: 'Mail', icon: 'mail' },
    { name: 'Message', icon: 'message' },
    { name: 'Copy', icon: 'copy2' },
    { name: 'Facebook', icon: 'facebook' },
    { name: 'Twitter', icon: 'twitter' },
  ];

  $scope.listItemClick = function($index) {
    var clickedItem = $scope.items[$index];
    $mdBottomSheet.hide(clickedItem);
  };
  $scope.showGridBottomSheet = function() {
    $scope.alert = '';
    $mdBottomSheet.show({
      templateUrl: 'bottom-sheet-grid-template.html',
      controller: function () {
                      return this;
      },
      preserveScope: true,
      bindToController: true,
      clickOutsideToClose: true
    }).then(function(clickedItem) {
      $mdToast.show(
            $mdToast.simple()
              .textContent(clickedItem['name'] + ' clicked!')
              .position('top right')
              .hideDelay(1500)
          );
    });
  };
})
.run(function($http, $templateCache) {

    var urls = [
      'img/icons/share-arrow.svg',
      'img/icons/upload.svg',
      'img/icons/copy.svg',
      'img/icons/print.svg',
      'img/icons/hangout.svg',
      'img/icons/mail.svg',
      'img/icons/message.svg',
      'img/icons/copy2.svg',
      'img/icons/facebook.svg',
      'img/icons/twitter.svg'
    ];

    angular.forEach(urls, function(url) {
      $http.get(url, {cache: $templateCache});
    });

  });

I can’t see the buttons/icons inside the sheet.

Fiddle: https://jsfiddle.net/uvkr9zwe/