无法将来自其他模板的表单加载到现有模块

时间:2018-03-07 11:02:14

标签: angularjs

我已经使用特定控制器实现了一个表单,然后将其存储在作用域对象中,然后我将该作用域对象分配给服务属性以共享n个控制器。在将数据分配给服务属性后,我将重定向到另一个页面,其中表单是他们的,并且它有一些字段,但我无法在网页中显示该表单。

示例:index.html:

<body ng-app="app" ng-controller="ctrl_1"> ... ..... </body>

main.js:

var app = angular.module("app",[]);

app.service("myService",function(){
    this.Details = "";
    this.setDetails = function(details){
        this.Details = details;
    };
    this.getDetails = function(){
        return this.Details;
    } });
在服务中传递数据后

app.controller("ctrl_1",function($scope,myService){我重定向到index2.html window.location("index2.html"); });

app.controller("ctrl_2",function($scope,myService){   });

index2.html:

<body ng-app="app" controller="ctrl_2"> ..`enter code here` ....enter code here </body>

通过这种方式我定义了,但我无法运行index2.html页面。

1 个答案:

答案 0 :(得分:0)

您需要一个路由模块,例如ngRouteui.router。他们将帮助您重定向到其他页面。以下是您的方案的快速演示:

var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider) {
  $routeProvider
    .when("/", {
      templateUrl: "index.html"
    })
    .when("/page2", {
      templateUrl: "index2.html"
    });
});
app.service("myService", function() {
  this.Details = "";
  this.setDetails = function(details) {
    this.Details = details;
  };
  this.getDetails = function() {
    return this.Details;
  }
});

app.controller("ctrl_1", function($scope, myService, $location) {
  $scope.redirect = function(path) {
    $location.url(path);
  }
});

app.controller("ctrl_2", function($scope, myService, $location) {
  $scope.redirect = function(path) {
    $location.url(path);
  }
});
<!DOCTYPE html>
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-route.js"></script>

<body>
  <div ng-view></div>

  <script type="text/ng-template" id="index.html">
    <div ng-controller="ctrl_1">
      Page 1 (index.html)
      <br>
      <button ng-click="redirect('/page2')">Redirect</button>
    </div>
  </script>
  <script type="text/ng-template" id="index2.html">
    <div ng-controller="ctrl_2">
      Page 2 (index2.html)
      <br>
      <button ng-click="redirect('/')">Go back</button>
    </div>
  </script>

</body>

</html>