[英]Angular JS does not work with Bootsrap and ASP.NET MVC
我正在嘗試非常簡單的AngularJS示例來發布用戶通過文本框輸入的數據。
我在做:
<div ng-controller="Subscribe">
<input type="text" ng-model="EmailAddress" />
<button class="btn btn-success" ng-click="send()">Subscribe</button>
<div>{{status}}</div>
</div>
@section FooterJS{
<script type="text/javascript">
function Subscribe($scope) {
$scope.send = function () {
//alert("sdf");
var _url = '/NewsLetter/Subscribe'
$http({ method: 'POST', url: _url, cache: $templateCache }).
success(function (data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
}
}
</script>
}
在Main Layout頁面中,我包含了以下js文件,在js文件之后,添加了FooterJS部分。
<script src="~/Scripts/jquery-2.0.3.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-resource.min.js"></script>
<script src="~/Scripts/bootstrap-lightbox.min.js"></script>
生成的輸出是http://gyazo.com/ad2a992d8dc2af106ca95956abffe1d5
當我單擊按鈕時什么也沒有發生。
沒弄錯是什么?,我是Angular JS的初學者。
$ http和$ templateCache尚未注入到控制器中。
function Subscribe($scope) {
應該改為
function Subscribe($scope, $http, $templateCache) {
有關角度依賴注入的更多信息,請參見http://docs.angularjs.org/guide/di
您需要確保有一個ng-app部分圍繞控制器(可能還有其他html代碼),如下所示:
<div ng-app>
... some html code here ...
<div ng-controller="Subscribe">
<input type="text" ng-model="EmailAddress" />
<button class="btn btn-success" ng-click="send()">Subscribe</button>
<div>{{status}}</div>
</div>
... more html code here ...
</div>
觀察結果 :我認為您正在實現幾種反模式。 AngularJS的主要目的之一是避免從像ASP.NET這樣的mvc框架生成渲染的html。 AngluarJS的哲學是使用它來使用靜態htmls文件創建單頁應用程序,因此表示層位於純靜態html,javascript和css文件上,因此最好不要使用MVC框架,而是使用API REST框架,例如Service Stack使用REST Web服務與表示層通信。
其次,您應避免執行“ @section FooterJS”操作,因為您將html模板邏輯與javascript代碼耦合在一起,該代碼應位於另一個文件中以提供更好的可維護性,您應該創建另一個javascript文件並使用來將其添加到html中。 <script>
標記,例如<script src="SubscribeCtrl.js">
等。
最后,我建議您按照本教程https://egghead.io/lessons/angularjs-controllers更好地了解angularjs控制器,我真的建議您觀看egghead提供的所有免費angularjs視頻,它們的確很棒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.