[英]AngularJS: Advice on architecture for changing DOM based on AJAX
Angular的網站上有一個簡單的示例:
function PhoneListCtrl($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}
但是我會執行比這更復雜的事情,即使在閱讀了許多Angular的文檔之后,我也不確定如何執行。 我需要根據ajax請求的結果執行一些DOM操作。 我應該如何構造該代碼? Angular的網站專門說:
不要將控制器用於:任何類型的DOM操作-控制器應僅包含業務邏輯。
好的...那我應該在哪里處理基於ajax返回數據的DOM操作呢? 我意識到他們的文檔這樣說:
如果必須執行自己的手動DOM操作,請將表示邏輯封裝在指令中。
但是我不確定如何將所有這些適當地粘合在一起。 我如何將所有這些放在一起,並以某種方式進行處理,使得如果再次發出AJAX請求,並且“模型”發生更改,則仍會執行相應的邏輯來執行DOM操作?
基本上,我問的是,如果不在控制器中,那么您將在哪里基於AJAX請求執行DOM操作?
如果您正在使用$ http或$ resource進行AJAX請求,則將此AJAX請求的結果注入到控制器的$ scope中。
有了指令,您可以在模型更改時監視$ ...因此,是的,使用指令是正確的方法!
例如HTML部分:
<!DOCTYPE html>
<html ng-app="App">
<head>
<link rel="stylesheet" href="style.css">
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MyController">
<h1>Usage Directive for model data change</h1>
<div>
<input directive type="text" ng-model="example"/>
</div>
</body>
</html>
腳本部分包含一個簡單的控制器和一個指令:
angular.module('App', []).controller('MyController', function($scope){
// In real prod app you'll use the $http API to get the data from the server
$scope.example = "Example data";
});
angular.module('App').directive('directive', function(){
return{
restrict: 'A',
link: function(scope, element, attrs){
scope.$watch(attrs.ngModel, function(newValue){
console.log(newValue);
})
}
}
});
如果運行此代碼並打開瀏覽器控制台(F12),然后更改輸入值,您將看到我們在您的范圍內使用偽指令和$ watch函數獲得了新值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.