EzDev.org

angular.js

HTML enhanced for web apps AngularJS — Superheroic JavaScript MVW Framework angularjs is what html would have been, had it been designed for building web-apps. declarative templates with data-binding, mvw, mvvm, mvc, dependency injection and great testability story all implemented with pure client-side javascript!


directive not showing template properly in AngularJS Bootstrap

I am using a custom directive to dynamically generate two columns in a row. Using just Bootstrap, I am able to get the design I want, it is seen below with html code.

It works

HTML:

<div class="col-md-6 border border-dark d-none d-md-block">
    <div class="row">
        <div class="col-md-6">
            <img class="img-fluid" src="pics/apple.png" />
        </div>
        <div class="col-md-6 align-self-center">
            <ul>
                <li>Name:APPLE</li>
                <li>Dimensions:THIS ONE</li>
            </ul>
        </div>
    </div>
</div>

Now when I use a custom directive with the template having the same exact HTML structure, it looks like this: It does not work anymore using directives

HTML:

<features pics="pics/apple.png" name="Iphone" dimensions="One"></features>

AngularJS:

app.directive('features',function(){
    var direc={};
    var link=function(scope,element,attributes){
        scope.pics=attributes["pics"];
        scope.name=attributes["name"];
        scope.dimensions=attributes["dimensions"];
    }
    direc.restrict="AE";
    direc.link=link;
    direc.template='<div class="col-md-6 border border-dark d-none d-md-block"><div class="row"><div class="col-md-6"><img class="img-fluid" src="{{pics}}" /></div><div class="col-md-6 align-self-center"><ul><li>Name:{{name}}</li><li>Dimensions:{{dimensions}}</li></ul></div></div></div>';
    direc.scope={};
    return direc;
})

Any idea why it does so? Thank you for reading.


Source: (StackOverflow)

AngularJS translate with UI Router

I have an application built with Angularjs using Angularjs Translate library - https://angular-translate.github.io/, and I have set it up with UI router because the current website has already been indexed by google with language versions like www.domain.com/en/us/ and I need to keep the same URL structure. The website has over 30 languages but it is a SPA (Single Page Application).

Below is my Javascript for the app configuration:

app.run(['$rootScope', '$translate', '$state', function ($rootScope, $translate, $state) {
    $rootScope.onChangeValue = function (e) {
        $rootScope.$broadcast("changeValue", e);
    };

    $rootScope.$on('$stateChangeSuccess', onStateChangeSuccess);

    function onStateChangeSuccess(event, toState, toParams) {
        var current = $translate.use();
        if (!current || current !== toParams.lang)
            $translate.use(toParams.lang);
    }
}]);

app.config(['$translateProvider', function ($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: '../languages/locale-',
        suffix: '.json'
    });
    $translateProvider.fallbackLanguage('en');
    $translateProvider.preferredLanguage('en');
    $translateProvider.useSanitizeValueStrategy('escape');
    $translateProvider.useCookieStorage();
}]);

app.config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('');

    $stateProvider.state('catalog', {
        url: '/{lang}',
        controller: "SudokuController",
        params: {
            lang: {
                value: function ($translate) {
                    return $translate.use();
                }
            }
        }
    });
}]);

and in the controller I have these functions:

    app.controller("SudokuController", ['$scope', 'Chronicle', '$timeout', '$cookies', '$translate', '$state', '$stateParams', function ($scope, Chronicle, $timeout, $cookies, $translate, $state, $stateParams) {

    $scope.params = $stateParams;
    $scope.changeLanguage = function (newLang) {
        var params = angular.extend($stateParams, { lang: newLang });

        $translate.use(newLang).then(function () {
            $state.transitionTo($state.current, params, {
                reload: true, inherit: false, notify: true
            });
        });
    }
}]);

Here is the HTML that is generating the nav with multiple languages:

<div class="language-dropdown">
    <ul class="country-list" ng-controller="navigationLanguages">
        <li class="country" ng-repeat="language in languagesMenu">
            <div class="country-flag" style="background-image: url('images/mk.png');"></div>
            <a ng-bind="language.Language" ng-click="changeLanguage(language.Code)"></a>
        </li>
    </ul>
</div>

So far I have achieved to add to the URL the chosen language, for instance, if I click on English I get www.domain.com/en, if I click on Spanish I get www.domain.com/es. But when I go directly to the www.domain.com/en I get Error 404 - Object not found!

  • How can I make so when the URL is inserted along with the language after the / to access the website with that particular language instead of showing Error 404.

    How to make the languages states like www.domain.com/en/us instead of www.domain.com/en (so it goes first the language code and then the country code)?

    Is it possible for these URLs/ languages to be crawlable by Google?


Source: (StackOverflow)

AngularJS and ui-router: wrong routes behaviour after refresh

I'm developing an application with AngujarJS and ui-router and I'm having a problem loading the routes. To facilitate the explanation I will delete parts of the code. My rotes file looks like this:

app.config(function($stateProvider, $urlRouterProvider, 
$locationProvider) {

$stateProvider
.state('dashboard', {
  url: '/dashboard',
  templateUrl : 'pages/dashboard.html',
  controller  : 'DashController'
})
.state('dashboard.vendas', {
  url: '/vendas',
  templateUrl : 'pages/vendas.html',
  controller  : 'vendasController'
})
;

$urlRouterProvider.otherwise('/');

$locationProvider.html5Mode({
      enabled: true,
      requireBase: false
      });
});

I load this route /dashboard after the user login. On this route, I load, among other things, an http method that returns the companies that the user will have access to, through the factory below:

app.factory("factoryEmpresas", 
function($http,urlBase,isAuthenticated) {
return {
    getEmpresas: function() {
        return $http({
            url: urlBase.getUrl() + '/empresas',
            method: "GET",
            headers: {
                'X-Token': isAuthenticated.getJWT()
            }
        }).then(function successCallback(response) {   
            return response.data;
        }, function errorCallback(response) {
            return response;
        });

    }
}
});

When accessing the route /vendas (which is related to the state dashboard.vendas), I make another http call using a variable that is in the factoryEmpresas return as follows:

app.factory("factoryVendas", 
function($http,urlBase,isAuthenticated) {
return {
    getVendas: function(id_empresa) {
        return $http({
            url: urlBase.getUrl() + '/vendas?id_empresa=' + id_empresa,
            method: "GET",
            headers: {
                'X-Token': isAuthenticated.getJWT()
            }
        }).then(function successCallback(response) {   
            return response.data;
        }, function errorCallback(response) {
            return response;
        });
    }
}
});

Everything works perfectly, until the user decides to refresh (F5) when on the route /vendas. At that moment the loading of the two routes /dashboad and /vendas is triggered. However, when making the http call at factoryVendas, the factoryDashboard has not yet returned the getEmpresas function. Thus, the variable "empresa_id" is not filled with the value that it should, thus resulting in an undefined call in place of "empresa_id".

The question I ask is, how can I make factorySales wait for the factoryDashboard to return so that I can make the call with the variable duly filled in?

Any help will be welcome.

Thank you!


Source: (StackOverflow)

Submitting forms with different controllers

I have these two forms for submitting data to newsfeed table, one is: controller for image path, and second is for: newsfeed content. Then I want to submit these two forms in one click and submit the first form than the second form (submit form one at a time)

<form id="form1" ng-submit="Submit();">
</form>

<form id="form2" ng-submit="newsfeed.regNewsfeed(regData);">
</form>

Source: (StackOverflow)

convert English number to bangla number in angularjs [closed]

I

var bengali = [০,১,২,৩,৪,৫,৬,৭,৮,৯];
 var eng = [0,1,2,3,4,5,6,7,8,9];

wanna show product price in bangla font like 435 to ৪৩৫


Source: (StackOverflow)

"Thinking in AngularJS" if I have a jQuery background? [closed]

Suppose I'm familiar with developing client-side applications in jQuery, but now I'd like to start using AngularJS. Can you describe the paradigm shift that is necessary? Here are a few questions that might help you frame an answer:

  • How do I architect and design client-side web applications differently? What is the biggest difference?
  • What should I stop doing/using; What should I start doing/using instead?
  • Are there any server-side considerations/restrictions?

I'm not looking for a detailed comparison between jQuery and AngularJS.


Source: (StackOverflow)

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

The API Reference Scope page says:

A scope can inherit from a parent scope.

The Developer Guide Scope page says:

A scope (prototypically) inherits properties from its parent scope.

So, does a child scope always prototypically inherit from its parent scope? Are there exceptions? When it does inherit, is it always normal JavaScript prototypal inheritance?


Source: (StackOverflow)

AngularJS-Slick is not working even after including all necessary scripts in proper order

I am making use of an angularJs-slick slider for my project to show some packages as a sliding feature.

I have included all the necessary files and dynamically getting packages via the controller.

Here the package is showing one after the other instead of in slider with the slide controller buttons. and the control buttons are not loaded into the DOM. any help appreciated. correct me if am doing anything wrong here. thank you

    <div class="row slick-container">
            <slick settings="responsiveConfig">
                {% verbatim %}
                    <div class="col-xs-11 col-xs-offset-0-5 col-sm-11 col-sm-offset-0-5">
                        <div class="row slick-container text-elegant">
                            <slick slides-to-show="4" slides-to-scroll="4">
                                <div class="col-sm-3 space-bottom-none slick-anchor space-top-none" ng-repeat="item in popularpackages">
                                    <div class="panel panel-default panel-elegant">
                                        <div class="panel-header text-center hidden-xs">
                                            <img class="img-responsive inline full-block" ng-src="/images/aa1.{{loop.index+1}}.jpg" />
                                        </div>
                                        <div class="panel-body">
                                            <a ng-click="trackPopularClick('{{item.test_name}}')" title="{{ item.test_name }}">
                                                <div class="text-center">
                                                    <div title="{{ item.test_name }}">
                                                        <h3 class="space-top-none text-heading text-primary text-ellipsis text-center">{{ item.test_name }}</h3>
                                                        <span class="text-sm text-muted">Best Suited Category:</span>
                                                        <img class="img-responsive inline"  style="height:1em;display:inline;border:0;" ng-src="/images/{{ item.item_icon }}.png"> <span class="text-sm text-muted">{{ item.item_name }}</span>
                                                        <div class="text-elegant text-heading text-muted text-center space-top-lg">
                                                            <span class="text-base text-center">{{ item.bundledTestsCount }} parameters</span></br>
                                                            <span>
                                                                INR
                                                                <del class="text-muted">{{ item.price }}</del>
                                                                <span class="text-secondary text-lg">{{ item.displayPrice }}</span>
                                                            </span>
                                                        </div>
                                                        <hr />
                                                        <span ng-repeat="organ in item.organCovered | split:',':0">
                                                            <img title="{{ organ }}" alt="{{ organ }}"
                                                                    class="inline img-responsive" ng-src="/images/organs/{{ organ|trim }}.png"
                                                                    style="height: 15px;">
                                                            <span class="text-primary">{{ organ|trim }}</span>
                                                        </span>
                                                        </br></br>
                                                        <a rel='nofollow' href="/packages/{{item.slug}}-in-{{locationCity}}">
                                                        <button class="btn-span blueBorderBtn btn-float-left">+ Know more</button>
                                                        </a>
                                                        <button class="btn btn-primary btn-float-right" ng-click="checkout(item.testLabId,locationCityId)">Book Now</button>
                                                    </div>
                                                </div>
                                            </a>
                                        </div>
                                    </div>
                                </slick>
                            </div>
                        </div>
                    </div>    
                {% endverbatim %}
            </slick>
        </div>

verbatims are used because I am using twig 
```JAVASCRIPTS: this is in the proper structure 
    angular.module('MT.app', [
        'slickCarousel'
    ])

    .controller ('popularTestsController', function (
            $scope,
        ) {
        $scope.responsiveConfig = {
            enabled: true,
            autoplay: true,
            draggable: false,
            autoplaySpeed: 3000,
            method: {},
            dots: false,
            infinite: false,
            speed: 300,
            slidesToShow: 3,
            slidesToScroll: 3,
            event: {
                beforeChange: function (event, slick, currentSlide, nextSlide) {
                },
                afterChange: function (event, slick, currentSlide, nextSlide) {
                }
            },
            responsive: [{
                breakpoint: 1024,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    infinite: true,
                    dots: true
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2
                }
            },
            {
                breakpoint: 480,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            }]
        };

    })

javascript is properly included in the js file, from module declaration to controller usage.
below css and JS cdn are included in the same order as I have mentioned below:
```CSS CDN 
    <link rel="stylesheet" rel='nofollow' href="//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.css"/>
    <link rel="stylesheet" rel='nofollow' href="//cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css"/>

```JS CDN 
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>   
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-slick-carousel/3.1.7/angular-slick.js"></script>

Source: (StackOverflow)

Working with $scope.$emit and .$on

How can I send my $scope object from one controller to another using .$emit and .$on methods?

function firstCtrl($scope)
{
    $scope.$emit('someEvent', [1,2,3]);
}

function secondCtrl($scope)
{
    $scope.$on('someEvent', function(mass) { console.log(mass); });
}

It doesn't work the way I think it should. How do $emit and $on work?


Source: (StackOverflow)

this vs $scope in AngularJS controllers

In the "Create Components" section of AngularJS's homepage, there is this example:

controller: function($scope, $element) {
  var panes = $scope.panes = [];
  $scope.select = function(pane) {
    angular.forEach(panes, function(pane) {
      pane.selected = false;
    });
    pane.selected = true;
  }
  this.addPane = function(pane) {
    if (panes.length == 0) $scope.select(pane);
    panes.push(pane);
  }
}

Notice how select method is added to $scope, but addPane method is added to this. If I change it to $scope.addPane, the code breaks.

The docs say that there in fact is a difference but don't mention what the difference is:

Previous versions of Angular (pre 1.0 RC) allowed you to use this interchangeably with the $scope method, but this is no longer the case. Inside of methods defined on the scope this and $scope are interchangeable (angular sets this to $scope), but not otherwise inside your controller constructor.

How does this and $scope work in AngularJS controllers?


Source: (StackOverflow)

Using scope.$watch and scope.$apply

I don't understand how to use scope.$watch and scope.$apply. The official documentation isn't helpful.

What I don't understand specifically:

  • Are they connected to the DOM?
  • How can I update DOM changes to the model?
  • What is the connection point between them?

I tried this tutorial but it takes the understanding of $watch and $apply for granted.

What do $apply and $watch do, and how do I use them appropriately?


Source: (StackOverflow)

Prevent error $digest already in progress when calling $scope.$apply()

I'm finding that I need to update the my page to my scope manually more and more since building an application in angular. The only way I know of to do this is to call $apply() from the scope of my controllers and directives. The problem with this is that it keeps throwing an error to the console that reads

Error: $digest already in progress

Does anyone know how to avoid this error or achieve the same thing but a different way?


Source: (StackOverflow)

How to fix "ReferenceError: Can't find variable: $jscomp" (phantomjs) or "ReferenceError: $jscomp is not defined" (firefox, chromium)?

After compiling javascript code with closure compiler (v20190729.0.0, previous versions too), I get ReferenceError: Can't find variable: $jscomp. Is there a solution that does not require to turn polyfills off with the option --rewrite_polyfills=false?


Source: (StackOverflow)

issue with using shared modules in angular

Hi I'm looking for if any one can help me out with my issue with sharing components in different modules in angular 9

I want to use component "PubEventCard" from "pub-events.module.ts" in another module named as "Home", I m exporting the component from pub-event module and importing the module in Home.module.ts file but I m unable to use the component as it gives an error

core.js:4061 ERROR TypeError: Cannot read property 'name' of undefined
    at PubEventPageComponent.push../src/app/routes/pub-event/pub-event-page/pub-event-page.component.ts.PubEventPageComponent.setSeo (pub-event-page.component.ts:59)

i console and directs to not found page. I am attaching my code and looking forward if any one can correct my mistake, thanks in advance

pub-event.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../../shared/shared.module';
import {Routes, RouterModule } from '@angular/router';

import { PubEventListComponent } from './pub-event-list/pub-event-list.component';
// import { PubEventPageComponent } from './pub-event-page/pub-event-page.component';
import { PubEventPageComponent } from './pub-event-page/pub-event-page.component';
import { PubEventCheckInComponent } from './pub-event-check-in/pub-event-check-in.component';
import { PubEventCardComponent } from './pub-event-card/pub-event-card.component';

const routes: Routes = [
    { path: '', component: PubEventListComponent }, 
    { path: ':event_id', component: PubEventPageComponent  },
    { path: ':event_id/order', loadChildren: './pub-event-buy/pub-event-buy.module#PubEventBuyModule'  },
    { path: ':event_id/check-in', component: PubEventCheckInComponent },
    { path: 'orders', loadChildren: './pub-event-order/pub-event-order.module#PubEventOrderModule'  },
    { path: 'order', loadChildren: './pub-event-order/pub-event-order.module#PubEventOrderModule'  },
];

@NgModule({
  imports: [
    CommonModule,
    SharedModule,
    RouterModule.forChild(routes),

  ],
  // c
  declarations: [PubEventListComponent,  PubEventPageComponent, PubEventCheckInComponent, PubEventCardComponent],
  exports: [RouterModule, PubEventCardComponent],
  providers: []
})
export class PubEventModule { }

Trying to import in Home.module.ts

import { NgModule } from '@angular/core';
import { SharedModule } from '../../shared/shared.module';
import { HomeComponent } from './home/home.component';
import { Routes, RouterModule } from '@angular/router';
import { UserProfileComponent } from './user-profile/user-profile.component';
import { FeedbackComponent } from './feedback/feedback.component';
import { GettingStartedComponent } from './getting-started/getting-started.component';
import { LandingComponent } from './landing/landing.component';
//import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { SwiperModule } from 'ngx-swiper-wrapper';
import { OrgBannerComponent } from './org-banner/org-banner.component';
import { EventBannerComponent } from './event-banner/event-banner.component';
//import { PubEventCardComponent } from '../pub-event/pub-event-card/pub-event-card.component';
import { PubEventModule } from '../pub-event/pub-event.module';



const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'user-profile', component: UserProfileComponent },
    { path: 'feedback', component: FeedbackComponent },
    { path: 'getting-started', component: GettingStartedComponent },
    { path: 'landing', component: LandingComponent },

];

@NgModule({
    imports: [
        SharedModule,
        //NgbModule,
        SwiperModule,
        RouterModule.forChild(routes),
        PubEventModule
    ],
    declarations: [HomeComponent, UserProfileComponent, FeedbackComponent, GettingStartedComponent, LandingComponent, OrgBannerComponent, EventBannerComponent,],
    providers:[

    ],
    exports: [
        RouterModule,SwiperModule,
        OrgBannerComponent,
        EventBannerComponent,
    ]
})
export class HomeModule { }

The component.html file I m trying to use in

<div>
    <div fxLayoutAlign.md="start center" fxLayoutAlign.sm="center center" fxLayout="row wrap" fxLayoutAlign="start center"
    fxLayoutGap="24px">
    <pub-event-card *ngFor="let event of events" [event]="event"  class="org-card"></pub-event-card>


  </div>
</div>

Source: (StackOverflow)

Does it make sense to use Require.js with Angular.js? [closed]

I'm a newbie to Angular.js and trying to understand how it's different from Backbone.js... We used to manage our packages dependencies with Require.js while using Backbone. Does it make sense to do the same with Angular.js?


Source: (StackOverflow)