2015-07-03 57 views
1

我是新的angularJS,即時嘗試調用我的MVC jsonresult獲取數據,因此填充列表,但我的GetLogs函數不會去MVC jsonresult/misc/getlogs(我也有完整的URL tryed)。代碼是:AngularJS不能調用MVC控制器

<body ng-app="Log"> 
<div ng-controller="MiscController"> 
    <ul ng-repeat="log in logs" class="notification-body"> 
     <li> 
      <span class="unread"> 
       <a href="javascript:void(0);" class="msg"> 
        <img src="/content/img/avatars/4.png" alt="" class="air air-top-left margin-top-5" width="40" height="40" /> 
        <span class="from">John Doe <i class="icon-paperclip"></i></span> 
        <time>2 minutes ago</time> 
        <span class="subject">{{log.Name}}</span> 
        <span class="msg-body">Hello again and thanks for being a part of the newsletter. </span> 
       </a> 
      </span> 
     </li> 
    </ul> 
</div> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     GetLogs(); 
    }); 

    function GetLogs() { 
     var app = angular.module("Log", []); 
     app.controller('MiscController', function ($scope, $http) { 
      $http.post("/misc/getlogs") 
      .success(function (data) { $scope.logs = data.logs; }); 
     }); 
    } 
</script> 

回答

1

你不應該調用getLogs()函數document.readyng-app將首先運行,並要求該模塊將拋出和模塊錯誤。

所以解決方案是在頁面加載時創建一個角度模塊。

<script type="text/javascript"> 

    var app = angular.module("Log", []); 
    app.controller('MiscController', function ($scope, $http) { 
     $http.post("/misc/getlogs") 
     .success(function (data) { $scope.logs = data.logs; }); 
    }); 
</script> 

更新

如果你想負荷角度在頁面上懶洋洋地那麼就使用angular.bootstrap將初始化元件上的角度默默。移動這種方法之前,你需要從你頁面刪除ng-app指令。

<script type="text/javascript"> 
    $(document).ready(function() { 
     GetLogs(); 
    }); 

    function GetLogs() { 
     var app = angular.module("Log", []); 
     app.controller('MiscController', function ($scope, $http) { 
      $http.post("/misc/getlogs") 
      .success(function (data) { $scope.logs = data.logs; }); 
     }); 
     angular.bootstrap(document.body, ['Log']) 
    } 
</script> 
+0

哦,謝謝我使用了該函數,因爲我需要從一個按鈕(用於刷新)調用它。無論如何,我無法達到我的jsonresult(或的ActionResult)不明白爲什麼 – Sauron

+0

@Sauron我認爲,如果你是從你的方法返回的JSON應該有'JSONBehaviour.AllowGet'&應該使用'$ http.get'而不是' POST' .. –

+0

你的「更新」的工作完美!最後,我可以達到jsonresult :)感謝的人 – Sauron