在Ionic 3中导入angularjs-scroll-glue指令遇Uncaught ReferenceError报错
First off, let's get to the root of the problem: you're trying to use angularjs-scroll-glue—a package built for AngularJS (1.x)—in an Ionic 3 app that uses Angular (2+). These are entirely separate frameworks, so the package is looking for a global angular variable that doesn't exist in your Angular-based Ionic project. That's exactly why you're seeing that error.
Here are two solid solutions to get the auto-scroll-to-bottom functionality working:
Solution 1: Use an Angular-compatible alternative
Skip the AngularJS package and go with ngx-scroll-glue, a port made specifically for Angular 2+. Here's how to set it up:
Install the package via npm:
npm install ngx-scroll-glue --saveImport the module into your
app.module.ts:import { ScrollGlueModule } from 'ngx-scroll-glue'; @NgModule({ imports: [ // ... your existing imports like BrowserModule, IonicModule ScrollGlueModule ] }) export class AppModule {}Add the directive to your template where you need auto-scrolling:
<div scroll-glue> <!-- Your dynamic content (like chat messages) goes here --> </div>
Solution 2: Build a custom directive (no external packages)
If you prefer not to add another dependency, you can create this functionality yourself with a simple directive:
Generate a new directive using the Ionic CLI:
ionic generate directive ScrollGlueReplace the code in
scroll-glue.directive.tswith this:import { Directive, ElementRef, OnInit, OnChanges, SimpleChanges } from '@angular/core'; @Directive({ selector: '[appScrollGlue]' }) export class ScrollGlueDirective implements OnInit, OnChanges { constructor(private el: ElementRef) { } ngOnInit() { this.scrollToBottom(); } ngOnChanges(changes: SimpleChanges) { this.scrollToBottom(); } private scrollToBottom() { const container = this.el.nativeElement; // Use setTimeout to ensure content has finished updating before scrolling setTimeout(() => { container.scrollTop = container.scrollHeight; }, 0); } }Register the directive in your
app.module.ts:import { ScrollGlueDirective } from '../directives/scroll-glue/scroll-glue.directive'; @NgModule({ declarations: [ // ... your existing components/pages ScrollGlueDirective ] }) export class AppModule {}Use it in your template:
<div appScrollGlue> <!-- Your dynamic content here --> </div>
Why your original approach failed
The angularjs-scroll-glue package depends on the global angular object from AngularJS to register its directive. Since Ionic 3 uses Angular (not AngularJS), this global variable doesn't exist in your app—hence the ReferenceError: angular is not defined.
内容的提问来源于stack exchange,提问作者astrakid932

