AngularJS (1) 宣告ng-app
在要開始學習angularJS之前,先玩一下這個範例吧↓
你輸入的是: {{ greet }}
- 提供了資料的雙向綁定,讓使用者輸入後直接更新網頁程式的變數。
- 即時預覽,使用者輸入後不需要重新整頁,增加網頁的親合度。
- Web 程式輕量化,減少開發負擔
介紹完angularjs後,接下來就要進入本文的重點寫程式啦。別擔心,我們當然會從簡單的開始學。
在<head>匯入AngularJS
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
</head>
ng-app 的基本宣告
ng-app 宣告了angularJS在HTML的作用範圍。當angularJS看見ng-app時,就會自動初始化(auto-bootstrap)此範圍內的腳本程式。請注意(ng-app的說明)!原則上,一個網頁只可以宣告一次ng-app。若是你想要網頁上同時有多個ng-app,需要手動宣告。
在<html>或<body>宣告
<html ng-app>
<body>
<div>
1 + 2 = {{1+2}}
</div>
</body>
</html>
<html>
<body ng-app>
<div>
1 + 2 = {{1+2}}
</div>
</body>
</html>
或者更直接地宣告在<div>
<html>
<body>
<div ng-app>
1 + 2 = {{1+2}}
</div>
</body>
</html>
宣告ng-app之後,用{{ }}表示angularJS要進行的計算式或是顯示變數,以上結果都會是
1 + 2 = {{1+2}}
ng-app 的基本宣告 完整版
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script>
var myApp = angular.module('myApp',[]);
</script>
</head>
<body ng-app="myApp">
<div>
1 + 2 = {{1+2}}
</div>
</body>
</html>
也可以顯示.js檔案的內部變數。
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller("IntroController", function($scope){
$scope.name = 'Lily';
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="IntroController">
Hello, I'm {{name}}
</div>
</body>
</html>
Hello, I'm {{name}}
ng-app內的範圍,需要定義ng-controller,留待下回解說。
留言
張貼留言