在控制器中添加$ location依赖项时,ng-click停止触发

时间:2016-05-04 08:54:30

标签: javascript angularjs

我试图从我的控制器运行ng-click功能。当我没有使用$ location依赖项时,它会触发ng-click函数。一旦将其添加到控制器,ng-click功能就不起作用。也没有显示任何错误。

我的应用

angular
  .module('MyApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider, $locationProvider) {

    $routeProvider
      .when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
      })
      .when('/in-the-community', {
        templateUrl: 'views/in-the-community.html',
        controller: 'CommunityCtrl'
      })
       .otherwise({
        redirectTo: '/'
      })


  });

当ng-click赢得“

”时,我的控制器
angular.module('MyApp')
  .controller('HomeCtrl', ['$location', '$scope', function ($scope, $location) {
    console.log('cheese');
    $scope.nextContent = function(element) {
        console.log($location);
        //$location.path('/' + (element.currentTarget.attributes[0].value));
    }
  }]);

我的控制器何时会触发ng-click事件

angular.module('MyApp')
  .controller('HomeCtrl', function ($scope) {
    $scope.nextContent = function(element) {
        console.log(element.currentTarget.attributes[0].value);
        //$location.path('/' + (element.currentTarget.attributes[0].value));
    }
  });

我的HTML标记

 <nav id="nav" class="nav" >
        <ul class="nav-list">
          <li><button data-location="card" ng-click="nextContent($event)">Card</button></li>
          <li><button data-location="heating-oil" ng-click="nextContent($event)">Heating Oil</button></li>

        </ul>
      </nav><!--end .nav-->

2 个答案:

答案 0 :(得分:2)

您混淆了注入变量的顺序。

尝试

angular.module('MyApp')
  .controller('HomeCtrl', ['$scope', '$location',  function ($scope, $location) {
    console.log('cheese');
    $scope.nextContent = function(element) {
        console.log($location);
        //$location.path('/' + (element.currentTarget.attributes[0].value));
    }
  }]);

答案 1 :(得分:1)

尝试更改

.controller('HomeCtrl', ['$location', '$scope', function ($scope, $location) {

.controller('HomeCtrl', ['$scope', '$location', function ($scope, $location) {