2013-10-28 63 views
0

我使用angularJS1.2路由功能來部分加載一些視圖。AngularJS不能從ng-view中訪問ng-click

var app = angular.module('app', ['ngAnimate', 'ngRoute']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { 
     $routeProvider.when('/profile/personalInfo', {templateUrl: '<?php echo base_url().'profile/personalInfo' ?>', controller: personalInfo}); 
     $routeProvider.when('/profile/myPlaces', {templateUrl: '<?php echo base_url().'profile/myPlaces' ?>', controller: myPlaces}); 
     $routeProvider.otherwise({redirectTo: '/profile/personalInfo'}); 
     $locationProvider.html5Mode(true); 
    }]); 

function personalInfo($scope, $http){ 
     console.log('personal info'); 
    } 

    function myPlaces($scope, $http){ 
     console.log('my places'); 
     $scope.places = []; 
     //then fill places via $http.post request 
     $scope.loadMore = function(){ 
     console.log('clicked'); 
     } 
    } 

這是我parial頁:

<div> 
    <h1>My Places Page</h1> 
    <div ng-repeat="place in places"> 
     <a href="" ng-click="loadMore()">load more</a> 
    </div> 
</div> 

路由已經成功完成,但是當我點擊鏈接調用loadMore,那麼這個錯誤出現在控制檯undefined is not a function。 有什麼問題,我該如何解決它?

回答

1

我發現了一個soluation,但我不知道這是soluation最優,但至少它解決了這個問題。 我創建了一個自定義的指令,如下面的

app.directive('whenClicked', function() { 
     return function(scope, elm, attr) { 
      var raw = elm[0]; 
      angular.element(raw).bind('click', function() { 
       console.log('clicked'); 
      }); 
     }; 
    }); 

,然後從部分頁面,您可以調用指令

<div> 
    <h1>My Places Page</h1> 
    <div ng-repeat="place in places"> 
     <a href="" when-clicked>load more</a> 
    </div> 
</div> 
+1

如果您需要一個針對您將在多個應用程序中使用的點擊事件的基本指令,那麼這可以工作。否則它是一個控制器函數,作爲mvc結構的一部分。控制器處理視圖(點擊)和數據(模型)之間的變化。 – KnowHowSolutions

0

使它成爲一個控制器:

app.controller('MyCtrl',function myPlaces($scope, $http){ 
    console.log('my places'); 
    $scope.places = []; 
    //then fill places via $http.post request 
    $scope.loadMore = function(){ 
    console.log('clicked'); 
    } 
}); 
+0

是什麼'OverviewCtrl'?你能提供更多的細節。 –

+0

我的錯。您必須將其重命名爲myPlaces ofcourse。我強烈建議看看http://www.egghead.io和角度文檔以獲取更多信息。 另外,你有沒有通過教程? – Sprottenwels