【问题标题】:Angular routes and views and controllers角度路由、视图和控制器
【发布时间】:2014-02-17 09:44:29
【问题描述】:

我正在尝试使用路由和视图制作一个非常简单的应用程序,当单击按钮时,它会显示测试文本变为“单击”。

我有一个带有 ng-view 的 index.html 文件,可以正确调用 test.html 视图。该视图应该使用带有简单模型的 testCtrl.js。

但是加载的时候,好像调用了view,但是scope有问题,或者控制器有问题。当我点击一个按钮时,单词 test 应该变成“click”,但什么也没有发生。

这里是 index.html

    <body ng-app="simtoolbelt">
    <div ng-view></div>



<script src="js/modules/angular-route.min.js"></script>
<script src="js/controllers/testCtrl.js"></script>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
  $(document).foundation();
</script>

这里是处理路由和视图的 app.js:

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

    simtoolbelt.config(['$routeProvider',
      function($routeProvider) {
      $routeProvider.
          when('/test', {
            templateUrl: 'views/test.html',
            controller: 'testCtrl'
          }).
          otherwise({
             redirectTo: '/test'
          });
    }]);

测试控制器:

    simtoolbelt.controller('testCtrl', ['$scope', function($scope){

  $scope.test = "test";
  $scope.change = function($scope){
    $scope.test = "Click";
  };

   }]);

最后是测试视图:

    <div ng-controller="testCtrl">
      <h1 ng-model="test">Le {{test}} fonctionne</h1>
      <button ng-click="change()">Click</button>
    </div>

所有这些都在本地主机中,我真的不知道我在错过什么......谢谢你们能给我的任何帮助!

【问题讨论】:

    标签: angularjs controller routes views angularjs-scope


    【解决方案1】:

    你的函数“change”接受参数“$scope”。在ng-click 中,您调用了一个不带参数的方法。

    change 方法中删除参数:

    $scope.change = function(){
     $scope.test = "Click";
    };
    

    此外,您的h1 标记中不需要ng-model 属性。

    【讨论】:

    • 感谢您的回答。但它仍然不起作用......我按照你告诉我的做了,我从函数中删除了范围参数,但仍然。
    • 你读过答案的第二部分吗? ng-model 仅用于双向数据绑定(在输入中,选择元素)。
    • 我跳过了它,你是对的,这就是问题所在!非常感谢!
    【解决方案2】:

    尝试将路由中的控制器定义更改为“仅控制器名称”,例如

    simtoolbelt.config(['$routeProvider',
      function($routeProvider) {
      $routeProvider.
          when('/test', {
            templateUrl: 'views/test.html',
            controller: 'testCtrl'
          }).
          otherwise({
             redirectTo: '/test'
          });
    }]);
    

    我还没有测试它,但它应该可以工作。

    【讨论】:

    • 好的,我想通了。由于“ng-model”属性,它不起作用。一旦我删除它,它就可以正常工作。所以我用

      Le {{test}} fonctionne

      而不是

      Le {{ test }} fonctionne

    猜你喜欢
    • 1970-01-01
    • 2017-11-10
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2014-02-02
    • 1970-01-01
    相关资源
    最近更新 更多