簡體   English   中英

Angular (1.4.7) ng-view 中的 JavaScript 不起作用

[英]JavaScript inside Angular's (1.4.7) ng-view doesn't work

我有一個進入 ng-view 的部分頁面,我有與該頁面無關的 JS 代碼,所以我希望它只包含在該頁面中,因為我只需要它並避免開銷我的 index.html,我嘗試使用ng-bind-html注入,但無效。

這里有一些代碼可以幫助理解發生了什么。

索引.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <base href="/">

    <title>Node and Angular App</title>

    <!-- CSS -->
    <link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">

    <!-- JS -->
    <script src="libs/angular/angular.min.js"></script>
    <script src="libs/angular-route/angular-route.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-sanitize.min.js"></script>

    <!-- ANGULAR CUSTOM -->
    <script src="js/controllers/TestCtrl.js"></script>
    <script src="js/appRoutes.js"></script>
    <script src="js/app.js"></script>

</head>
<body ng-app="sampleApp">
    <div class="container">
        <nav>
            <a href="/test">Test</a>
       </nav>

        <!-- ANGULAR DYNAMIC CONTENT -->
       <div ng-view></div>
    </div>
</body>
</html>

測試控件.js

angular.module('TestCtrl', ['ngSanitize']).controller('TestController', function($scope) {

  var str = '<h1>this shows</h1><script>alert("hello")</script><h1>this doesn\'t show</h1>';

  $scope.content = function() { return str; }
});

測試.html

<div class="jumbotron" ng-bind-html="content()"></div>

appRoutes.js

angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {

  $routeProvider

  .when('/test', {
    templateUrl: 'views/test.html',
    controller: 'TestController'
  })

 $locationProvider.html5Mode(true);
}]);

應用程序.js

var app = angular.module('sampleApp', ['ngRoute', 'appRoutes', 'TestCtrl']);

我不完全理解您的問題,但如果您想將 html 注入視圖,請嘗試將 ngSanitize 添加到模塊中的依賴項列表中,您可以擁有:

controller("mainCtrl", ['$sce', function($sce){
    //function that returns trusted html
    this.htmlStuff = function(){
        return $sce.trustAsHtml("<p>Html String</p>");
    }
}]);

那么在你看來,你可以有

<div ng-controller='mainCtrl as main'>
    <div ng-bind-html="main.htmlStuff()"></div>
</div>

如果這不是你的意思,那么你必須改寫這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM