1

私は最近 angularJS の学習を開始し、ng-view ディレクティブの問題に遭遇しました。この質問が素朴すぎる場合はお詫び申し上げます。

これは私の index.html ファイルです。ご覧のとおり、ng-view ディレクティブを使用して、index.html ファイルから一部の html コードを抽出しています。

<!doctype html>
<html lang="en" ng-app="phonecat">
<head>
  <meta charset="utf-8">
  <title>My first app!</title>

  <script src="lib/angular/angular.js"></script>
  <script src="js/app.js"></script>
  <script src="js/directives.js"> </script>
  <script src="js/controllers.js"></script>
</head>
<body>
    <div ng-view></div>
</body>
</html>

これは私の app.js ファイルです。すべての URL に同じ部分テンプレートを使用しています。

angular.module('phonecat', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/phones', {templateUrl: 'partials/searchbox.html',   controller: PhoneListCtrl}).
      otherwise({templateUrl: 'partials/searchbox.html',   controller: PhoneListCtrl});
}]);

これは私のsearchbox.htmlです

<div id="container">
  <input type="text" name="s" id="s" float-up="{perspective: '100px', x: '150%'}"/>
</div>

そして最後に、これは私のディレクティブ.jsファイルです:

'use strict';

var myAppModule = angular.module('phonecat', []);

myAppModule.directive('floatUp', function() {
     return {
        // Restrict it to be an attribute in this case
          restrict: 'A',
        // responsible for registering DOM listeners as well as updating the DOM
          link: function($scope, element, attrs) {
             console.log("test successful");
          }
     };
 });

これをブラウザで実行すると、floatUp ディレクティブのリンク機能が呼び出されません。index.html ページのレンダリングされた html を見ると、次のようになります (ng-view は検索ボックスの html を置き換えていないことに注意してください)。

<!DOCTYPE html>
<html class="ng-scope" lang="en" ng-app="phonecat">
<head>
<meta charset="utf-8">
<title>My first app!</title>
<script src="lib/angular/angular.js">
<style type="text/css">
<script src="js/app.js">
<script src="js/directives.js">
</head>
<body>
<div ng-view=""></div>
</body>
</html>

その他の観察:

  1. index.htmlファイルからdirectives.jsを削除すると、ng-viewは完璧に機能し、検索ボックスは正常に表示されます。
  2. searchbox.html コンテンツを index.html ファイルにコピー ペーストすると、リンク機能が正しく呼び出されます。

これは既知の問題ですか? カスタム ディレクティブが ng-view を台無しにして無駄にします。ここに質問を投稿する前に大規模なグーグル検索を行ったのですが、適切な回答が見つかりませんでした。

4

1 に答える 1

5

この行を directives.js から移動します

var myAppModule = angular.module('phonecat', []);

app.jsの先頭へ

そうすれば、新しいインスタンスを作成するのではなく、常に同じ angular モジュール インスタンスで作業できます。

すべてのコントローラー、ディレクティブ、および構成は、myApModule.controller (または .config、または .directive) になります。

また、app.js では、controller: 'PhoneListCtrl'PhoneListCtrl がまだ定義されていないため、ルート内のコントローラーへの参照は文字列である必要があります。

controllers.js は提供されていませんが、次のようになります。

myAppModule.controller('PhoneListCtrl', ['$scope', function($scope) {
    //Controller code here
}]);

apps.js は次のようになります。

myAppModule.
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/phones', {templateUrl: 'partials/searchbox.html',   controller: 'PhoneListCtrl'}).
      otherwise({templateUrl: 'partials/searchbox.html',   controller: 'PhoneListCtrl'});
}]);
于 2013-07-20T07:35:52.820 に答える