AngularJS - 使用不同控制器的路由导致空$ scope

时间:2017-04-01 08:32:21

标签: angularjs

这是路由的.js文件:

var app = angular.module('WebApp', ['ngRoute']);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
  // Home
  .when("/", { templateUrl: "partials/kalendar.php", controller: "Ctrl" })
  .when("/logout", { templateUrl: "partials/logout.php", controller: "PageCtrl" })
  .otherwise({
    controller: function () {
        window.location.replace('/');
    },
    template: "<div></div>"
  });
}]);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function ($scope) {
        console.log("Page Controller reporting for duty.");
});

/**
 * Controls calendar view
 */
app.controller('Ctrl', function ($scope) {
        console.log("Controller reporting for duty.");
$scope.updateDuration = function () {
        alert($scope.dateIn);
}
});

这是我的kalendar.php的一部分:

<div>
<label>Datum:</label>
<div class="input-group input-append date">
     <input type="text" class="span2 form-control" ng-model="dateIn">
     <span class="input-group-addon">
           <span class="glyphicon glyphicon-th-large"></span>
     </span>
</div>
</div>

当我运行程序时,会调用页面控制器(“控制器报告以执行任务。”在控制台中显示),但警报不起作用,因为$ scope.dateIn未定义。请帮我找错。

1 个答案:

答案 0 :(得分:0)

你在Html中调用updateDuration函数吗?确保你从htmm调用你的函数如下

&#13;
&#13;
var app = angular.module('WebApp', ['ngRoute']);



/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function ($scope) {
        console.log("Page Controller reporting for duty.");
});

/**
 * Controls calendar view
 */
app.controller('Ctrl', function ($scope) {
        console.log("Controller reporting for duty.");
$scope.updateDuration = function () {
        alert($scope.dateIn);
}
});
&#13;
<!DOCTYPE html>
<html ng-app="WebApp">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <div>
<label>Datum:</label>
<div class="input-group input-append date">
     <input type="text" class="span2 form-control" ng-model="dateIn">
     <span class="input-group-addon">
           <span class="glyphicon glyphicon-th-large"></span>
     </span>
     <button type="button" ng-click="updateDuration() ">check me</button>
</div>
</div>
  </body>

</html>
&#13;
&#13;
&#13;

在这里,我设法通过按钮点击来调用该功能。