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>

最后这是我的 directives.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 的顶部

这样,您总是使用相同的角度模块实例,而不是创建它的新实例。

您的所有控制器、指令和配置都将是 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 回答