標籤:
這幾天開始學習Angular這個MVC架構, 邊看官網文檔和youtube視頻邊做執行個體, 現在整理下自己的學習所得與大家分享, 也希望有Angular的大牛們來指教和探討.
我們設想一個最基本的Web應用情境: 從伺服器擷取資料,通過這些資料來動態渲染我們的頁面. 假設我們目前需要擷取一組團隊所有成員的資訊並且顯示, 團隊成員的資訊有成員名字, 年齡.
(樣本的控制項在頁面上的)
首先我們需要為我們所需要渲染的頁面寫一個簡單的模板:
建立這個控制項的時候我使用的是flatui所設計的擴充bootstrap的一套css. 大家可以去這裡下載免費的flatui版本: https://github.com/designmodo/Flat-UI/archive/master.zip
<!doctype html><html><head> <meta charset="utf-8"> <link rel="stylesheet" href="/flatui/css/vendor/bootstrap.min.css"> <link rel="stylesheet" href="/flatui/css/flat-ui.min.css"> <script src="/js/angular/angular.min.js"></script> <script src="/js/mine.js"></script></head><body data-ng-app="zzUSRDirective" style="padding-top:40px"> <div class="container" data-ng-controller="row-ctrl"></div></body></html>
我們在於body處我們定義了一個標籤 data-ng-app並且給他命名為"zzUSRDirective", 這個標籤定義了一個angular的模型, 我將其理解為一個MVC封閉域, 我們將圍繞這個data-ng-app來展開.
開啟我們的js檔案mine.js, 敲入以下代碼:
1 (function(angular) { 2 angular.module(‘zzUSRDirective‘, []) 3 .controller(‘row-ctrl‘, [‘$scope‘, ‘$http‘, ‘$compile‘, ‘$element‘, 4 function($scope, $http, $compile, $element) { 5 $http.get(‘http://localhost:8080/users‘).success(function(json) { 6 $scope.json = json; 7 var html = 8 ‘<div data-ng-repeat="line in json" class="row">‘+ 9 ‘<div data-ng-repeat="user in line" class="col-md-3">‘+10 ‘<zzuserbox index="{{$parent.$index*3+$index}}" get="getbyidx"></zzuserbox>‘+11 ‘</div>‘+12 ‘</div>‘;13 $element.append(html);14 $compile($element.contents())($scope); 15 });16 $scope.getbyidx = function(idx) {17 var outidx = Math.floor(idx/3);18 var innidx = idx%3;19 return $scope.json[outidx][innidx];20 };21 }])22 .directive(‘zzuserbox‘, function() {23 return {24 scope : {25 get : ‘&‘26 },27 restrict : ‘E‘,28 templateUrl : ‘box.html‘,29 link : function($scope, $element, $attr) {30 $scope.json = $scope.get()(parseInt($attr.index));31 $scope.amnt = $scope.json.amnt;32 $scope.name = $scope.json.name;33 },34 controller : function($scope) { 35 }36 };37 });38 })(window.angular);
AngularJS 建立一個簡單可互動的控制項(一)