简体   繁体   中英

Why I cannot use JS file inside Angular app?

I am trying to include some js methods stored in a file in an angular application.Unfortunately i can not make the browser see the js file.
I have looked at this SO post and followed the instructions but the browser does not see the file ( Sources ) section.



Js file

 function  toggleModal(id) {
        var modal = document.getElementById(id);
        $("#" + id).modal('toggle');
    }

    function setPag(tableId) {
        $(tableId).DataTable();
    }

My file is located inside:

Root/
  assets/
    js/
      scr.js

Usage in Component

declare function setPag(id:string):any;
declare function toggleModal(id:string):any;

@Component({
  selector: 'index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
     public toggle(id:string){
        toggleModal(id);
     }
     public setPage(id:string)
     {
        setPag(id);
     }
}

Angular.json
-Scripts section

"architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/AnubisUI",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/assets"

            ],

            "scripts": [
              "./src/assets/js/scr.js",
              "node_modules/chart.js/dist/Chart.js",
              "node_modules/hammerjs/hammer.min.js"
            ]
          }

Try this to see if work for you

import * as helper from 'assets/js/scr.js'

@Component({
  selector: 'index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
     public toggle(id:string){
        helper.toggleModal(id);
     }
     public setPage(id:string)
     {
        helper.setPag(id);
     }
}

Side note: Every static file should be add into asset folder so that you can import to your angular code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM