简体   繁体   中英

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

I have a partial page that goes inside the ng-view and I have JS code related to nothing other than that page and so I'd like for it to be included in that page only since I only need it there and to avoid overhead in my index.html, I tried injection like using ng-bind-html that didn't work.

Here's some code to help understand what's going on.

index.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>

TestCtrl.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; }
});

test.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);
}]);

app.js

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

I don't fully understand your question but if you want to inject html into your view, try adding ngSanitize to the list of dependencies in your module, them you can have:

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

then in your view, you can have

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

if this isn't what you meant, then you have to rephrase the question

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