2016-09-30 5 views
3

Есть некоторые проблемы с использованием скриптовых тегов (<script>) на угловом 2, с которым я сталкиваюсь.Angular2 remove tags tags

Первый: Я понимаю, что угловой 2 удаляет теги сценариев из шаблонов. Я преодолел эту проблему, написав свои скрипты в index.html. Тем не менее, запись всех скриптов в index.html делает код нечитаемым. Как я могу решить эту проблему ?

Second: Когда загружается первый раз index.html, мой скрипт работает (написан в index.html). Но после маршрутизации некоторых других шаблонов и обратно в index.html мой скрипт не работает. Я думаю, что проблема связана с маршрутизацией, но я не уверен.

index.html

<html> 
<head> 

    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 

    <base href="/"/> 

    <link rel="stylesheet" href="styles.css"> 

    <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> 
    <link href="bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet" /> 
    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script> 



    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> 
    <link href="bower_components/material-cards/dist/material-cards.css" rel="stylesheet" /> 
    <script src="bower_components/material-cards/js/jquery.material-cards.js"></script> 
    <script> 
     $(function() { 
      $('.material-card') 
       .materialCard({ 
        icon_close: 'fa-chevron-left', 
        icon_open: 'fa-thumbs-o-up', 
        icon_spin: 'fa-spin-fast', 
        card_activator: 'click' 
       }); 

      // $('.active-with-click .material-card').materialCard(); 

      window.setTimeout(function() { 
        $('.material-card').materialCard(); 
       }, 
       2000); 


     }); 
    </script> 


    <link href="bower_components/alertify.js/themes/alertify.core.css" rel="stylesheet"/> 
    <link href="bower_components/alertify.js/themes/alertify.bootstrap.css" rel="stylesheet"/> 
    <script src="bower_components/alertify.js/lib/alertify.min.js"></script> 
    <!-- Polyfill(s) for older browsers --> 
    <script src="node_modules/core-js/client/shim.min.js"></script> 
    <script src="node_modules/zone.js/dist/zone.js"></script> 
    <script src="node_modules/reflect-metadata/Reflect.js"></script> 
    <script src="node_modules/systemjs/dist/system.src.js"></script> 

    <script src="systemjs.config.js"></script> 
    <script src="https://code.angularjs.org/2.0.0-alpha.46/http.dev.js"></script> 

    <script> 
     System.import('app').catch(function (err) { console.error(err); }); 
    </script> 

</head> 
<body> 
<my-app> 

</my-app> 
</body> 

</html> 

app.component.ts

import { Component, ViewContainerRef } from '@angular/core'; 

@Component({ 
    selector: 'my-app', 

    template: ` 
      <navbar></navbar> 
      <router-outlet></router-outlet> 
       ` 
}) 

export class AppComponent { 
    constructor(private viewContainerRef: ViewContainerRef) { 
     // You need this small hack in order to catch application root view container ref 
     this.viewContainerRef = viewContainerRef; 
    } 

    getNotification(evt) { 
     // <child (notifyParent)="getNotification($event)"></child> 
     console.log(evt); 
    } 
} 

movies.component.ts

import { Component, Directive, OnInit, ViewContainerRef, ViewChild, ContentChildren } from '@angular/core'; 
import { MoviesService } from "./movies.service"; 
import { HttpModule } from '@angular/http'; 
import { ActivatedRoute, Router } from '@angular/router'; 
import { ModalDirective } from 'ng2-bootstrap'; 
import { NotificationService } from '../Shared/notification.service'; 


@Component({ 
    selector: 'movies2', 
    templateUrl: '/templates/movies.component.html', 
    providers: [MoviesService] 
}) 
export class MoviesComponent implements OnInit { 

    isLoading = true; 
    movies: any = []; 
    selectedMovie: any = {}; 

    constructor(private _moviesService: MoviesService, private router: Router, private notificationService: NotificationService) { 
    } 

    ngOnInit() { 
     this.GetMovies(); 
    } 


    AddMovie() { 
     this.router.navigate(['/newmovie']); 
    } 

    GetMovies() { 
     this._moviesService.getMovies().subscribe(p => { 
      this.movies = p; 
     }); 
    } 

    SelectMovie(mv: any) { 
     this.selectedMovie = mv; 
    } 

    removeMovie(val: any) { 
     this.notificationService.openConfirmationDialog('Are you sure you want to delete ' + val.MovieName + ' ?', 
      () => { 
       this._moviesService.deleteMovie(val).subscribe(res => { 
        this.notificationService.printSuccessMessage(val.MovieName + ' has been deleted.'); 
        this.GetMovies(); 
       }, error => { 
        this.notificationService.printErrorMessage(error); 
       }); 
      }); 
    } 

    removeMovieV2(val: any) { 
     this._moviesService.deleteMovie(val).subscribe(res => { 
      this.notificationService.printSuccessMessage(val.MovieName + ' has been deleted.'); 
      this.GetMovies(); 
     }, error => { 
      this.notificationService.printErrorMessage(error); 
     }); 
    } 
} 

movies.component.html

<section class="container"> 

    <div class="row active-with-click"> 
     <div class="col-md-4 col-sm-6 col-xs-12"> 
      <article class="material-card Red"> 
       <h2> 
        <span>Christopher Walken</span> 
        <strong> 
         <i class="fa fa-fw fa-star"></i> 
         The Deer Hunter 
        </strong> 
       </h2> 
       <div class="mc-content"> 
        <div class="img-container"> 
         <img class="img-responsive" src="https://dl.dropboxusercontent.com/u/2691310/github/material-card/thumb-christopher-walken.jpg"> 
        </div> 
        <div class="mc-description"> 
         He has appeared in more than 100 films and television shows, including The Deer Hunter, Annie Hall, The Prophecy trilogy, The Dogs of War ... 
        </div> 
       </div> 
       <a class="mc-btn-action"> 
        <i class="fa fa-bars"></i> 
       </a> 
       <div class="mc-footer"> 
        <h4> 
         Social 
        </h4> 
        <a class="fa fa-fw fa-facebook"></a> 
        <a class="fa fa-fw fa-twitter"></a> 
        <a class="fa fa-fw fa-linkedin"></a> 
        <a class="fa fa-fw fa-google-plus"></a> 
       </div> 
      </article> 
     </div> 
     <div class="col-md-4 col-sm-6 col-xs-12"> 
      <article class="material-card Pink"> 
       <h2> 
        <span>Sean Penn</span> 
        <strong> 
         <i class="fa fa-fw fa-star"></i> 
         Mystic River 
        </strong> 
       </h2> 
       <div class="mc-content"> 
        <div class="img-container"> 
         <img class="img-responsive" src="https://dl.dropboxusercontent.com/u/2691310/github/material-card/thumb-sean-penn.jpg"> 
        </div> 
        <div class="mc-description"> 
         He has won two Academy Awards, for his roles in the mystery drama Mystic River (2003) and the biopic Milk (2008). Penn began his acting career in television with a brief appearance in a 1974 episode of Little House on the Prairie ... 
        </div> 
       </div> 
       <a class="mc-btn-action"> 
        <i class="fa fa-bars"></i> 
       </a> 
       <div class="mc-footer"> 
        <h4> 
         Social 
        </h4> 
        <a class="fa fa-fw fa-facebook"></a> 
        <a class="fa fa-fw fa-twitter"></a> 
        <a class="fa fa-fw fa-linkedin"></a> 
        <a class="fa fa-fw fa-google-plus"></a> 
       </div> 
      </article> 
     </div> 
    </div> 
</section> 
+0

Вы можете написать скрипт в 'app.component' -> стартовом компоненте. Это поможет? –

+0

Трудно сказать, не видя кода. Если речь идет о вашем собственном коде, чем просто написать его в TypeScript с компонентами или службами. Если речь идет о загрузке JS-библиотек, используйте require.js или аналогичные, чтобы включить код. –

+0

Я добавил код. – hsyn

ответ

-1

Официальный сайт angular2 говорит, что «мы удаляем теги сценария для обеспечения безопасности», но использование сценариев не написано

+0

Я не знаю, отвечает ли это на вопросы ... Разработайте больше на том, что вы пытаетесь сказать ... –