簡體   English   中英

AngularJS未在首頁視圖上加載

[英]AngularJS not loading on first page view

我在基於Rails 4構建的應用程序中使用AngularJS。我遇到的問題是,當我第一次重定向到頁面時,它不會加載任何js。 如果我輸入特定的URL或刷新頁面,則可以正常工作。 在Chrome控制台中,出現錯誤:

Uncaught Error: No module:  angular.js?body=1:1212

這是我的application.js文件:

    // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require angular
//= require_tree .


var Sampleblog = angular.module('Sampleblog', ['ngResource'])

$(document).on('page:load', function() {
  return $('[ng-app]').each(function() {
    var module;
    module = $(this).attr('ng-app');
    return angular.bootstrap(this, [module]);
  });
});

相關視圖文件:

<h1>Related Tweets</h1>

<div ng-app>
    <div ng-controller="TermCtrl">
      <span>{{remaining()}} of {{terms.length}} selected</span>
      <ul class="unstyled">
        <li ng-repeat="term in terms">
          <input type="checkbox" ng-model="term.select">
          <span class="select-{{term.select}}">{{term.text}}</span>
        </li>
      </ul>
      <form ng-submit="addTerm()">
        <input type="text" ng-model="termText"  size="30"
               placeholder="add new term here">
        <input class="btn-primary" type="submit" value="add">
      </form>
    </div>
</div>

<%= link_to 'Back to Posts', posts_path, type: "button", class: "btn btn-primary" %>

以及相關的.js文件

function TermCtrl($scope) {

    $scope.terms = [
    {text:'Placeholder1', select:true},
    {text:'Placeholder2', select:false}];

  $scope.addTerm = function() {
    $scope.terms.push({text:$scope.termText, select:false});
    $scope.termText = '';
  };

  $scope.remaining = function() {
    var count = 0;
    angular.forEach($scope.terms, function(term) {
      count += term.select ? 1 : 0;
    });
    return count;
  };
}
TermCtrl.$inject = ['$scope'];

任何幫助,將不勝感激!

您只需要告訴angular您要在ng-app加載哪個模塊:

<div ng-app="Sampleblog">

否則,它不知道您要加載此代碼:

angular.module('Sampleblog', ['ngResource'])

暫無
暫無

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

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