如何有条件地在Angular中包含脚本元素

时间:2016-09-08 13:42:23

标签: javascript angularjs angularjs-directive

我试图在我的网页上有条件地加入聊天:

import Foundation

class MovieDataBase
{
    static let sharedInstance = MovieDataBase()
    private init() {}
    //creating a singleton for the MovieDataStore

    var movies = [Movie]()
    //array to store all the movie objects from the json

    let movieSearchTerms = ["love", "fantasy", "romance", "mystery", "thriller", "musical", "family", "horror", "sci-fi"]

    func getMoviesWithCompletion(completion: () -> ()) {

        let randomNum = arc4random_uniform(UInt32(movieSearchTerms.count))

        OMDBAPIClient.getMovieResultsFromSearch(self.movieSearchTerms[Int(randomNum)]) { (arrayOfMovies) in
            for singleMovie in arrayOfMovies
            {

                let neededTitle = singleMovie["title"] as? String
                let neededYear = singleMovie["year"] as? String
                let neededImbdID = singleMovie["imdbID"] as? String
                let neededType = singleMovie["type"] as? String
                let neededPosterURL = singleMovie["posterURL"] as? String

                guard let
                    unwrappedTitle = neededTitle,
                    unwrappedYear = neededType,
                    unwrappedImbdID = neededImbdID,
                    unwrappedType = neededType,
                    unwrappedPosterURL = neededPosterURL

                    else { print("AN ERROR OCCURRED HERE"); return }

                var movie = Movie.init(title: unwrappedTitle, year: singleMovie["year"], imdbID: singleMovie["imbdID"], type: singleMovie["type"], posterURL: singleMovie["posterURL"])

                movies.append(movie)
            }
            completion()
        }

}


}

但似乎聊天脚本在<body ng-app="myApp"> <!-- some code --> <script type="text/javascript" ng-if="expression"> window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s= d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set. _.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8"); $.src="//v2.zopim.com/?my-zopim-id";z.t=+new Date;$. type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script"); </script> </body> 指令之前执行。

如何让我的Angular应用首先检查条件,然后从ng-if代码执行脚本?

3 个答案:

答案 0 :(得分:2)

可以通过一个技巧来实现:

  <script ng-if="..." type="{{ 'text/javascript' }}">
    ...
  </script>

绑定将阻止脚本以正常方式执行。

请注意,由于Angular的jqLit​​e实现如何处理<script>元素的方式,上述内容仅在加载jQuery时(Angular之前)才有效。

更干净的方式是一个与上面<script>相同的指令,但有一些安全措施可以防止多次执行(请注意,将<script>放入指令的模板对jQuery的要求与上面的解决方案)。

答案 1 :(得分:1)

内联Javascript将始终优先于Angular(首先由浏览器解析)。最好的方法是使用条件或创建指令在控制器中注入/执行javascript。

答案 2 :(得分:0)

一种原生且轻量级的方法,即没有jQuery,没有Angular指令,将使用类似https://github.com/anywhichway/scriptswitch的东西。