单击按钮时,单击不点击

时间:2017-01-11 21:28:57

标签: angularjs

有人告诉我,当我运行下面的Angular代码时,当我点击按钮时,它不会加载页面。即使我做了一个简单的警报,它似乎也没有用。

知道我在这里做错了什么吗?

的JavaScript

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

    app.config(function($routeProvider) {
        $routeProvider.
          when('/', {controller:Test, templateUrl:'test/part1'}).
          when('/details', {controller:Test, templateUrl:'test/part2'}).
          otherwise({redirectTo:'/'});
    });

    function grab ($scope, $location) {
         $scope.reserve = function (id) {
         $location.path('/details/'+id);
    };

HTML

<body ng-app="app">
    <button id="btt" type="button" ng-click="grab(2)">Click to grab</button>
</body>

3 个答案:

答案 0 :(得分:3)

控制器在哪里?

函数抓取应该在控制器中,你也不能在$ scope之外调用grab。所以

  • 抓取必须重构为$scope.grab = function($location)

  • 在控制器'Test'

  • 内移动

答案 1 :(得分:2)

请为正文定义一个控制器,然后将函数抓取添加到$ scope

    <body ng-app="app" ng-controller="testCtrl">

        app.controller('testCtrl', ['$scope', '$location', function($scope, $location){
                 $scope.grab = function(id) { 
                     $location.path('/details/'+id);
                 }
        }])

答案 2 :(得分:1)

我的头顶像是:

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

        app.config(function($routeProvider) {
            $routeProvider.
              when('/', {controller:Test, templateUrl:'test/part1'}).
              when('/details', {controller:Test, templateUrl:'test/part2'}).
              otherwise({redirectTo:'/'});
        });

    app.controller('Test', ['$scope', '$location', function Test($scope, $location) {
        $scope.grab = function (id) {{
             $location.path('/details/'+id);
        };
    }]);