通过ng-template进行角度路由

时间:2014-08-23 13:25:33

标签: angularjs routing

你好我做错了什么。我是角度js的新手,我使用ng-template进行路径查看。

myApp.config(['$routeProvider','$locationProvider',function($routeProvider,$locationPro    vider) {
    $routeProvider.
      when('/', {
        templateUrl: 'add.html',
        controller: 'myAppCtrl'
      }).
      when('/edit',{
        templateUrl:'edit.html',
        controller:'myAppCtrl'
      }).
       otherwise({
        redirectTo: '/'
      });
$locationProvider.html5Mode(true);
   }]);
}])

但它不起作用。请帮我 。

下面是我的html部分

<body ng-controller="myAppCtrl">
<div ng-view>
<script type="text/ng-template" id="add.html">
<div>
<input type="text" ng-model="$storage.myname"/>
<input type="text" ng-model="$storage.myid"/>
<input type="number" ng-model="$storage.mynumber"/>
<button ng-click="submit();"> submit </button>
</div>
</script>
</div>

2 个答案:

答案 0 :(得分:0)

你混淆了几件事:

  1. 您在身体中定义的控制器(ng-controller="my AppController")也被定义为路线的控制器。我怀疑你想要一个或另一个,但不是两个。
  2. 包含模板的脚本标记位于将替换的div内(<div ng-view>)。 ng-view div应为空(<div ng-view></div>),并在其外部定义模板,可能在标题中。

答案 1 :(得分:0)

我仔细查看了你的代码,为你的路由找到了解决方案 Fiddle 这是代码

//html
    <div ng-app="app">
      <div ng-controller="MainCntl">
        Choose:
          <a href="/add">add</a> |
          <a href="/edit">Edit</a> |
        <div ng-view></div>
        <hr />
          <pre>$location.path() = {{$location.path()}}</pre>
     </div>
     <script type="text/ng-template" id="add.html">
        Add
      </script>
      <script type="text/ng-template" id="edit.html">
       Edit
      </script>
    </div>
//app.js

    var myApp = angular.module('app', [], function($routeProvider, $locationProvider) {
      $routeProvider
      .when('/add', {
        templateUrl: 'add.html',
        controller: MainCntl
      })
      .when('/edit', {
        templateUrl: 'edit.html',
        controller: MainCntl,
      });
         // configure html5 to get links working on jsfiddle
      $locationProvider.html5Mode(true);
    });
    function MainCntl($scope, $route, $routeParams, $location) {
    }