ionic-framework - RIP Tutorial

56
ionic-framework #ionic- framework

Transcript of ionic-framework - RIP Tutorial

ionic-framework

#ionic-

framework

1

1: 2

2

2

Examples 2

2

1.npmIonic FrameworkCordovaIonicCordova 2

2. 3

3.Ionic 3

3

Ionic Framework Hello World App 5

YoYeomanIonic Cloud 6

6

Ionic 6

6

YeomanIonic FrameworkwebappsWebScaffolding 6

Web 7

IonicWeb 7

8

8

9

// 9

10

10

11

2: “”“” 12

Examples 12

12

3: Ionic - jshintgulp-jshint 13

13

linting 13

Examples 13

gulp 13

.jshintrc 13

Makefile 14

4: Ionicons 15

15

Examples 15

15

15

5: YeomanIonic Cloud 16

Examples 16

YoYeomanIonic Cloud 16

16

Ionic 16

16

YeomanIonic FrameworkwebappsWebScaffolding 16

Web 17

IonicWeb 17

18

18

19

// 19

20

20

21

6: Ionic 22

Examples 22

Ionic App 22

Ionic App 22

22

Github Repo 22

Codepen URL 22

22

/ 22

7: Ionic App 23

Examples 23

Ionic App 23

1. 23

2. 23

Live Reload App 23

runemulate/ 23

3. 24

4. 24

4.1 24

8: Ionic App 25

25

25

Examples 26

26

LiveReload 26

26

IP 26

26

/ 27

9: 28

28

28

Examples 28

28

10: IonicEcmaScript 6 29

Examples 29

gulp-babelgulp-plumber 29

11: Ionic 30

Examples 30

Ionic 30

12: Ionic 31

Examples 31

wwwWeb 31

13: Ionic 32

32

Examples 32

32

Ionic 3 35

14: Ionic 38

Examples 38

macOS 38

15: AngularJS 39

39

Examples 39

39

39

39

39

39

16: CLI 41

41

41

41

41

Examples 42

jshintbefore_prepareJavascript 42

17: CSS 44

44

Examples 44

44

44

45

45

45

46

47

18: ionic.io 48

Examples 48

48

19: Http 49

Examples 49

n 49

50

You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: ionic-framework

It is an unofficial and free ionic-framework ebook created for educational purposes. All the content is extracted from Stack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official ionic-framework.

The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified. All trademarks and registered trademarks are the property of their respective company owners.

Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected]

https://riptutorial.com/zh-TW/home 1

1:

IonicHTMLCSSJavaScript。“”。

IonicAngularJS。。 IonicCSS / SASSJavascript UI Extensions 。CLI。

“”。。 Ionic 。IonicWeb。

IonicApache Cordova。Cordova .Cordova。 trigger.ioCordova。

1.3.1“” 2016512

1.3.0“” 2016421

1.2.0“ - zeren” 2015129

1.1.0“xenon-xerus” 2015813

1.0.0“ - ” 2015512

Examples

1.npmIonic FrameworkCordovaIonicCordova

Node.js.Node.js。

MacXcode iOs Simulator。

MacWindowsCordovaIonic

$ npm install -g cordova ionic

Macsudo

$ sudo npm install -g cordova ionic

CordovaIonic

$ npm update -g cordova ionic

$ sudo npm update -g cordova ionic

AndroidiOS。

https://riptutorial.com/zh-TW/home 2

iOSMac OS X.Ionic CLIiOSios-sim npm

$ sudo npm -g install ios-sim

2.

Ionic。

$ ionic start myApp blank

$ ionic start myApp tabs

$ ionic start myApp sidemenu

3.Ionic

iOSAndroidIonic

$ ionic serve --lab

ionic serve --labUIJavascript

$ ionic serve

Ionic

$ cd myApp $ ionic platform add ios android $ ionic build ios $ ionic emulate ios

androidiosAndroid

$ ionic build android $ ionic emulate android

USBAndroidIonic

$ ionic run android

USBiOSIonic

$ ionic run ios --device

https://riptutorial.com/zh-TW/home 3

Angular JSWeb。

http //ionicframework.com/

http //ionicframework.com/docs/

NPMCordova。

Npde JSNPM。

Apache CordovaNPM

npm install -g cordova

NPMCordova。

npm install -g ionic

*。

Ionic Framework

ionic start myproject

ionic start myproject [template_name]

Ionic

tabs 。

sidemenu 。

blank 。

myproject。

ionic serve --lab

ionic serve

ionic platform [Platform Name] ionic build [Platform Name] ionic emulate [platform name]

androidios。

https://riptutorial.com/zh-TW/home 4

ionic run [platform name]

ionic --help

ionic help

cli 。

CSS 。

Javascript API 。

Playground 。

...

Ionic Framework Hello World App

Hello World App

ionic start HelloWorld blank // create new project cd HelloWorld // get into HelloWorld directory

subline / webstrome IDEHelloWorldwww / ditectoryindex.html○

<body ng-app="starter"> <ion-pane> <ion-header-bar class="bar-stable"> <h1 class="title">Ionic Hello World App</h1> </ion-header-bar> <ion-content> <div class="center">Hello World..!</div> </ion-content> </ion-pane> </body>

ionic serve // run the app in browser

ionic platform add android // add android platform ionic platform add ios // add ios platform

https://riptutorial.com/zh-TW/home 5

adb devices // to check devices is connected ionic run android // to run on android devices ionic run ios // to run on ios devices

livereload•

ionic run android -c -s -l // to check app in live reload with console.

YoYeomanIonic Cloud

Ionic。

Ionic。。

Ionic Platform。。YeomanIonicIonic Platform。

YeomanIonicIonic Platform Web ClientIonic Platform。Ionic DeployIonic AnalyticsIonic Push。

Web /。

/。

AngularJs https //docs.angularjs.org/guide•IonicFramework http //ionicframework.com/docs/guide•Yeomanhttp //yeoman.io/codelab/index.html•https //github.com/diegonetto/generator-ionic•https //ionic.io/platform•

YeomanIonic FrameworkwebappsWebScaffolding

Node.jsChromeV8 JavaScriptJavaScript。 npmJavaScript。http://nodejs.orgNodenpm

https://riptutorial.com/zh-TW/home 6

$ npm install npm –g $ npm install -g yo

Yeoman。

$ yo ionic [app-name]

package.json devDependencies

"grunt-string-replace": "^1.2.1"

bower.json

"ionic-platform-web-client": "^0.7.1"

Gruntfile.js“js” 。index.html 。

grunt.initConfig({ yeoman: {………… scripts: 'js', ………… } })

$ bower install && npm install $ grunt $ grunt serve $ cordova platform add android $ grunt build:android --debug

Web

IonicWeb。

Ionic。IonicIonicWebIonic.io。

$ ionic io init

app.js'ionic.service.core'。Gruntfile.jsgrunt'ionicSettings' 。

grunt.initConfig({ ionicSettings: JSON.stringify(grunt.file.readJSON('./.io-config.json')), ionicIoBundlePath: 'www/bower_components/ionic-platform-web-client/dist/ionic.io.bundle.min.js',

https://riptutorial.com/zh-TW/home 7

'string-replace': { ionicSettings: { files: { '<%= ionicIoBundlePath %>': '<%= ionicIoBundlePath %>', }, options: { replacements: [ { pattern: '"IONIC_SETTINGS_STRING_START";"IONIC_SETTINGS_STRING_END"', replacement: '"IONIC_SETTINGS_STRING_START";var settings =<%= ionicSettings %>; return { get: function(setting) { if (settings[setting]) { return settings[setting]; } return null; } };"IONIC_SETTINGS_STRING_END";' } ] } } }, copy: { ionicPlatform:{ expand: true, cwd: 'app/bower_components/ionic-platform-web-client/dist/', src: ['**'], dest: 'www/bower_components/ionic-platform-web-client/dist' } } }); grunt.registerTask('ionicSettings', ['copy:ionicPlatform','string-replace:ionicSettings']);

init'ionicSettings' 。index.html 。

<script src="bower_components/ionic-platform-web-client/dist/ionic.io.bundle.min.js"></script>

$ Grunt serve

Ionic Deploy。Ionic Deploy。

Gruntfile.jsgrunt'deploy' 。

grunt.registerTask('deploy', function () { return grunt.task.run(['init', 'ionic:upload' + this.args.join()]); });

$ ionic plugin add ionic-plugin-deploy

https://riptutorial.com/zh-TW/home 8

var deploy = new Ionic.Deploy(); // Check Ionic Deploy for new code deploy.check().then(function(hasUpdate) { }, function(err) { }); // Update app code with new release from Ionic Deploy deploy.update().then(function(result) { }, function(error) { }, function(progress) { });

apk。“ grunt deploy ”。。

apps.ionic.io。deploy。。

$ grunt build:android --debug $ grunt deploy --note "release notes" $ grunt deploy --note "release notes" --deploy=production

//。

。Ionic Analytics。

app.jsionic.service.core“ionic.service.analytics”。

$ionicAnalytics.register();

Ionic Analytics。。$ionicAnalytics.track(eventType, eventData) 。

$ionicAnalytics.track('User Login', { user: $scope.user });

ion-track-tap。ion-track-data。

<button ion-track-tap="eventType" ion-track-data="expression"></button>

apps.ionic.io

。。

https://riptutorial.com/zh-TW/home 9

。。

。。。

。。

Pulse。

Ionic PushAPI。

Android

AndroidGoogle Cloud Messaging GCM。Google Developers Console。 。GCMIDGCM 。

API ManagerGoogle Cloud Messaging API 。CredentialsCreate credentialsAPI KeyServer Key。APIAccept requests from ...Create 。API

Ionic - > 。 。 。

AndroidGoogle Cloud MessagingGoogle Developer ConsoleAPI 。 - > API 。API 。API 。

$ ionic plugin add phonegap-plugin-push --variable SENDER_ID="GCM_PROJECT_NUMBER" $ ionic config set gcm_key <your-gcm-project-number> $ ionic config set dev_push false $ ionic io init

phonegap-plugin-pushAndroid32+

app.jsionic.service.core' ionic.service.push '

。。

$ionicPush.init({ debug: true, onNotification: function (notification) { console.log'token:', notification.payload); }, onRegister: function (token) { console.log('Device Token:', token); $ionicPush.saveToken(token); // persist the token in the Ionic Platform } }); $ionicPush.register();

https://riptutorial.com/zh-TW/home 10

$ grunt build:android --debug

Ionic Push。。

curl -X POST -H "Authorization: Bearer API_TOKEN" -H "Content-Type: application/json" -d '{ "tokens": ["DEVICE_TOKEN"], "profile": "PROFILE_TAG", "notification": { "message": "Hello World!" "android": { "title": "Hi User", "message": "An update is available for your App", "payload": { "update": true } } } }' "https://api.ionic.io/push/notifications"

iOSIonic Push。iOShttp://docs.ionic.io/v2.0.0-beta/docs/ios-push-profiles

IonicApp: │ │ bower.json │ Gruntfile.js │ package.json │ └───app │ index.html │ ├───js │ app.js │ controllers.js │ └───templates home.html menu.html

。。

https://riptutorial.com/zh-TW/ionic-framework/topic/893/

https://riptutorial.com/zh-TW/home 11

2: “”“”

Examples

platforms / PLATFORMXCodeAndroid Eclipse。IDE。www $ cordova prepare iosiOS

www。platforms/ios/www。

- XCodeionic prepareiOSXCode。

ionic buildAndroid.apkionic emulate。

“”“” https://riptutorial.com/zh-TW/ionic-framework/topic/2911/-----

https://riptutorial.com/zh-TW/home 12

3: Ionic - jshintgulp-jshint

。。

linting

“Linting。” - “Linting”

package.json。/

npm install jshint --save-dev npm install jshint-stylish --save-dev npm install gulp-jshint --save-dev

Examples

gulp

gulpfile.js。gulp

gulp.task('lint', function() { return gulp.src(['./www/js/**/*.js']) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')) });

'www''js'。JavaScript。“views”

gulp.task('lint', function() { return gulp.src(['./www/js/**/*.js','./www/views/**/*.js']) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')) });

1) /**/*.js - This syntax means to look at all the js files in the subfolders too 2) .jshintrc - This is a configuration file that we will create in the next example.

.jshintrc

app“.jshintrc”package.json。

*windows“jshintrc.txt”。“.jshintrc”。 。

。jshint。

https://riptutorial.com/zh-TW/home 13

{ "predef": [ "window", "console", "cordova", "device", "alert", "document", "debug", "setServiceVars", "StatusBar", "config" ], "globals": { "angular" : false, "myApp" : false, "myControllers" : false, "myDirectives" : false, "localStorage" : false, "navigator" : false, "emit" : false, "atob" : false, "moment" : false, "btoa" : false }, "node" : true }

Makefile

“Makefile”1.

2.

android: gulp lint gulp sass ionic run android --device ios: gulp lint gulp sass ionic build ios

lintsass。

“android --device”

Android: make android iOS : make ios

Ionic - jshintgulp-jshint https://riptutorial.com/zh-TW/ionic-framework/topic/4889/ionic----jshintgulp-jshint

https://riptutorial.com/zh-TW/home 14

4: Ionicons

Web。CSS.IoniconsIonic Framework100。。

IoniconsIonics CSS。

http //ionicons.com/

Examples

<i>。 Ionic。

<i class="icon ion-home"></i>

IonicCSSIonicons。<div>range。。

<div class="item range"> <i class="icon ion-volume-low"></i> <input type="range" name="volume"> <i class="icon ion-volume-high"></i> </div>

IonicIonicon。 tabs-striped tabs-color-assertive。<i>div。

<div class="tabs-striped tabs-color-assertive"> <div class="tabs"> <a class="tab-item" href="#"> <i class="icon ion-home"></i> Home </a> <a class="tab-item" href="#"> <i class="icon ion-gear-b"></i> Settings </a> </div>

Ionicons https://riptutorial.com/zh-TW/ionic-framework/topic/5886/ionicons

https://riptutorial.com/zh-TW/home 15

5: YeomanIonic Cloud

Examples

YoYeomanIonic Cloud

Ionic。

Ionic。。

Ionic Platform。。YeomanIonicIonic Platform。

YeomanIonicIonic Platform Web ClientIonic Platform。Ionic DeployIonic AnalyticsIonic Push。

Web /。

/。

AngularJs https //docs.angularjs.org/guide•IonicFramework http //ionicframework.com/docs/guide•Yeomanhttp //yeoman.io/codelab/index.html•https //github.com/diegonetto/generator-ionic•https //ionic.io/platform•

YeomanIonic FrameworkwebappsWebScaffolding

Node.jsChromeV8 JavaScriptJavaScript。 npmJavaScript。http://nodejs.orgNodenpm

$ npm install npm –g $ npm install -g yo

https://riptutorial.com/zh-TW/home 16

Yeoman。

$ yo ionic [app-name]

package.json devDependencies

"grunt-string-replace": "^1.2.1"

bower.json

"ionic-platform-web-client": "^0.7.1"

Gruntfile.js“js” 。index.html 。

grunt.initConfig({ yeoman: {………… scripts: 'js', ………… } })

$ bower install && npm install $ grunt $ grunt serve $ cordova platform add android $ grunt build:android --debug

Web

IonicWeb。

Ionic。IonicIonicWebIonic.io。

$ ionic io init

app.js'ionic.service.core'。Gruntfile.jsgrunt'ionicSettings' 。

grunt.initConfig({ ionicSettings: JSON.stringify(grunt.file.readJSON('./.io-config.json')), ionicIoBundlePath: 'www/bower_components/ionic-platform-web-client/dist/ionic.io.bundle.min.js', 'string-replace': { ionicSettings: { files: {

https://riptutorial.com/zh-TW/home 17

'<%= ionicIoBundlePath %>': '<%= ionicIoBundlePath %>', }, options: { replacements: [ { pattern: '"IONIC_SETTINGS_STRING_START";"IONIC_SETTINGS_STRING_END"', replacement: '"IONIC_SETTINGS_STRING_START";var settings =<%= ionicSettings %>; return { get: function(setting) { if (settings[setting]) { return settings[setting]; } return null; } };"IONIC_SETTINGS_STRING_END";' } ] } } }, copy: { ionicPlatform:{ expand: true, cwd: 'app/bower_components/ionic-platform-web-client/dist/', src: ['**'], dest: 'www/bower_components/ionic-platform-web-client/dist' } } }); grunt.registerTask('ionicSettings', ['copy:ionicPlatform','string-replace:ionicSettings']);

init'ionicSettings' 。index.html 。

<script src="bower_components/ionic-platform-web-client/dist/ionic.io.bundle.min.js"></script>

$ Grunt serve

Ionic Deploy。Ionic Deploy。

Gruntfile.jsgrunt'deploy' 。

grunt.registerTask('deploy', function () { return grunt.task.run(['init', 'ionic:upload' + this.args.join()]); });

$ ionic plugin add ionic-plugin-deploy

var deploy = new Ionic.Deploy();

https://riptutorial.com/zh-TW/home 18

// Check Ionic Deploy for new code deploy.check().then(function(hasUpdate) { }, function(err) { }); // Update app code with new release from Ionic Deploy deploy.update().then(function(result) { }, function(error) { }, function(progress) { });

apk。“ grunt deploy ”。。

apps.ionic.io。deploy。。

$ grunt build:android --debug $ grunt deploy --note "release notes" $ grunt deploy --note "release notes" --deploy=production

//。

。Ionic Analytics。

app.jsionic.service.core“ionic.service.analytics”。

$ionicAnalytics.register();

Ionic Analytics。。$ionicAnalytics.track(eventType, eventData) 。

$ionicAnalytics.track('User Login', { user: $scope.user });

ion-track-tap。ion-track-data。

<button ion-track-tap="eventType" ion-track-data="expression"></button>

apps.ionic.io

。。

。。

https://riptutorial.com/zh-TW/home 19

。。。

。。

Pulse。

Ionic PushAPI。

Android

AndroidGoogle Cloud Messaging GCM。Google Developers Console。 。GCMIDGCM 。

API ManagerGoogle Cloud Messaging API 。CredentialsCreate credentialsAPI KeyServer Key。APIAccept requests from ...Create 。API

Ionic - > 。 。 。

AndroidGoogle Cloud MessagingGoogle Developer ConsoleAPI 。 - > API 。API 。API 。

$ ionic plugin add phonegap-plugin-push --variable SENDER_ID="GCM_PROJECT_NUMBER" $ ionic config set gcm_key <your-gcm-project-number> $ ionic config set dev_push false $ ionic io init

phonegap-plugin-pushAndroid32+

app.jsionic.service.core' ionic.service.push '

。。

$ionicPush.init({ debug: true, onNotification: function (notification) { console.log'token:', notification.payload); }, onRegister: function (token) { console.log('Device Token:', token); $ionicPush.saveToken(token); // persist the token in the Ionic Platform } }); $ionicPush.register();

$ grunt build:android --debug

https://riptutorial.com/zh-TW/home 20

Ionic Push。。

curl -X POST -H "Authorization: Bearer API_TOKEN" -H "Content-Type: application/json" -d '{ "tokens": ["DEVICE_TOKEN"], "profile": "PROFILE_TAG", "notification": { "message": "Hello World!" "android": { "title": "Hi User", "message": "An update is available for your App", "payload": { "update": true } } } }' "https://api.ionic.io/push/notifications"

iOSIonic Push。iOShttp://docs.ionic.io/v2.0.0-beta/docs/ios-push-profiles

IonicApp: │ │ bower.json │ Gruntfile.js │ package.json │ └───app │ index.html │ ├───js │ app.js │ controllers.js │ └───templates home.html menu.html

。。

YeomanIonic Cloud https://riptutorial.com/zh-TW/ionic-framework/topic/6389/yeomanionic-cloud

https://riptutorial.com/zh-TW/home 21

6: Ionic

Examples

Ionic App

Ionic App

$ ionic start myapp [template]

GithubCodepen。Cordovawww。

sidemenu•

Github Repo

Github repo url https //github.com/driftyco/ionic-starter-tabs•Ionic starter repos•

Codepen URL

Codepen[ http://codepen.io/ionic/pen/odqCz] [1 ]•

Codepen•

/

--appname, -a ....... Human readable name for the app (Use quotes around the name) --id, -i ............ Package name set in the <widget id> config ex: com.mycompany.myapp --no-cordova, -w .... Do not create an app targeted for Cordova

Ionic https://riptutorial.com/zh-TW/ionic-framework/topic/3945/ionic

https://riptutorial.com/zh-TW/home 22

7: Ionic App

Examples

Ionic App

1.

iOS

$ ionic platform add ios

$ ionic platform add android

$ ionic platform add windows

2.

iOS

$ ionic build ios

$ ionic build android

$ ionic build windows

Live Reload App

runemulate/。--livereload 。ionic serve 。。。Web 。

--consolelogs-c/。--serverlogs-s。

runemulate/

[--livereload|-l] ....... Live Reload app dev files from the device (beta) [--consolelogs|-c] ...... Print app console logs to Ionic CLI (live reload req.) [--serverlogs|-s] ....... Print dev server logs to Ionic CLI (live reload req.) [--port|-p] ............. Dev server HTTP port (8100 default, live reload req.) [--livereload-port|-i] .. Live Reload port (35729 default, live reload req.) [--debug|--release]

CLI

https://riptutorial.com/zh-TW/home 23

restart or r to restart the client app from the root goto or g and a url to have the app navigate to the given url consolelogs or c to enable/disable console log output serverlogs or s to enable/disable server log output quit or q to shutdown the server and exit

3.

Ionic。run --emulator。

iOS

$ ionic emulate ios [options]

$ ionic emulate android [options]

$ ionic emulate windows [options]

AVDChrome。Chrome。

chrome://inspect/#devices

4.

Ionic。/。

iOS

$ ionic run ios [options]

$ ionic run android [options]

$ ionic run windows [options]

4.1。$ ionic run [ios/android/windows] --target="[target-name]"

$ adb devices/。

Ionic App https://riptutorial.com/zh-TW/ionic-framework/topic/4175/ionic-app

https://riptutorial.com/zh-TW/home 24

8: Ionic App

CameraVibrationIonic Native。CordonicIonicAndroidiOSWindows Mobile API。

Camera

cd src mkdir mocks cd mocks touch camera-mock.ts

camera-mock.ts

export class CameraMock { getPicture(params) { return new Promise((resolve, reject) => { resolve("BASE_64_IMAGE_DATA"); }); } }

src/app.module.ts“

import { CameraMock } from "../mocks/camera-mock";

@NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, CameraMock, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {}

https://riptutorial.com/zh-TW/home 25

Examples

ionic serveapp dev。。LiveReload。。 ionic serve。

$ ionic serve [options]

chromeAVDMobileschrome。

chrome://inspect/#devices

LiveReload

LiveReloadwww/www/lib/ 。ionic.projectwatchPatterns。

{ "name": "myApp", "app_id": "", "watchPatterns": [ "www/js/*", "!www/css/**/*" ] }

globGruntglobbing 。

$ ionic setup sass

SassgulpStartupTasks gulpStartupTasksionic.projectwatchPatterns ionic.projectgulpStartupTasks 。

Ionic Lab http://ionicframework.com/img/blog/lab.png

ionic serveiOSAndroid。

$ ionic serve --lab

IP

。--address。

$ ionic serve --address 68.54.96.105

servehttp。API。httpapiNo 'Access-Control-Allow-Origin' header is present on the requested

resourceNo 'Access-Control-Allow-Origin' header is present on the requested resource 。

ionic.project。

path URL。•

https://riptutorial.com/zh-TW/home 26

proxyUrl url。•

{ "name": "appname", "email": "", "app_id": "", "proxies": [ { "path": "/v1", "proxyUrl": "https://api.instagram.com/v1" } ] }

http://localhost:8100/v1https://api.instagram.com/v1

angular.module('starter.controllers', []) .constant('InstagramApiUrl', '') // .constant('InstagramApiUrl','https://api.instagram.com') //In production, make this the real URL .controller('FeedCtrl', function($scope, $http, InstagramApiUrl) { $scope.feed = null; $http.get(InstagramApiUrl + '/v1/media/search?client_id=1&lat=48&lng=2.294351').then(function(data) { console.log('data ' , data) $scope.feed = data; }) })

/

[--consolelogs|-c] ...... Print app console logs to Ionic CLI [--serverlogs|-s] ....... Print dev server logs to Ionic CLI [--port|-p] ............. Dev server HTTP port (8100 default) [--livereload-port|-i] .. Live Reload port (35729 default) [--nobrowser|-b] ........ Disable launching a browser [--nolivereload|-r] ..... Do not start live reload [--noproxy|-x] .......... Do not add proxies

Ionic App https://riptutorial.com/zh-TW/ionic-framework/topic/3256/ionic-app

https://riptutorial.com/zh-TW/home 27

9:

title: '', //。

cssClass: '' // StringCSS

subTitle: '' //。

template: '' //html。

templateUrl: '' //htmlURL。

scope: null, //。。

Ionic Popup。

Examples

// An alert dialog $scope.showAlert = function() { var alertPopup = $ionicPopup.alert({ title: 'Don\'t eat that!', template: 'It might taste good' }); alertPopup.then(function(res) { console.log('Hello your first example.'); }); }; });

https://riptutorial.com/zh-TW/ionic-framework/topic/6461/

https://riptutorial.com/zh-TW/home 28

10: IonicEcmaScript 6

Examples

gulp-babelgulp-plumber

IonicGulpgulp-babelgulp-plumber。

npm install --save-dev gulp-babel gulp-plumber

babelgulpfile.js

//... var babel = require("gulp-babel"); var plumber = require("gulp-plumber"); var paths = { es6: ['./src/es6/*.js'], sass: ['./scss/**/*.scss'] }; gulp.task('default', ['babel', 'sass']); gulp.task("babel", function () { return gulp.src(paths.es6) .pipe(plumber()) .pipe(babel()) .pipe(gulp.dest("www/js")); }); //... gulp.task('watch', function() { gulp.watch(paths.es6, ['babel']); gulp.watch(paths.sass, ['sass']); }); //...

ionic.project

"gulpStartupTasks": [ "babel", "sass", "watch" ],

ionic serve 。

IonicEcmaScript 6 https://riptutorial.com/zh-TW/ionic-framework/topic/4847/ionicecmascript-6-

https://riptutorial.com/zh-TW/home 29

11: Ionic

Examples

Ionic

;MySQLPostgresMSSQL...。 。

。AngularAngular。

RESTfulAPI。

PHPGoPython...。

RESTfulAPIAngular$resource$httpAngular。

Angular$httpGiphy API

var search = 'cats'; var link = 'http://api.giphy.com/v1/gifs/search?api_key=dc6zaTOxFJmzC&amp;q=' + search; $http.get(link).then(function(result){ console.log(result); });

Ionic https://riptutorial.com/zh-TW/ionic-framework/topic/4003/ionic

https://riptutorial.com/zh-TW/home 30

12: Ionic

Examples

wwwWeb

Ionic 1.2

Cordovawww。

Ionic 1“”“” IonicCSSHTML。

Ionic https://riptutorial.com/zh-TW/ionic-framework/topic/4001/ionic

https://riptutorial.com/zh-TW/home 31

13: Ionic

Examples

index.html

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *"/> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title></title> <link href="lib/ionic/css/ionic.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above <link href="css/ionic.app.css" rel="stylesheet"> --> <!-- ionic/angularjs js --> <script src="lib/ionic/js/ionic.bundle.js"></script> <!-- cordova script (this will be a 404 during development) --> <script src="js/ng-cordova.min.js"></script> <script src="cordova.js"></script> <!-- your app's js --> <script src="js/app.js"></script> <script src="js/controllers.js"></script> <script src="js/services.js"></script> </head> <body ng-app="starter"> <ion-content class="has-header padding" ng-controller="ImageController"> <button class="button button-full button-energized" ng-click="addMedia()"> Add image </button> <button class="button button-full button-positive" ng-click="sendEmail()"> Send mail </button> <br><br> <ion-scroll direction="y" style="height:200px; min-height: 200px; overflow: scroll; white-space: nowrap;"> <img ng-repeat="image in images track by $index" ng-src="data:image/jpeg;base64,{{image}}" style="height:200px; padding: 5px 5px 5px 5px;"/> </ion-scroll> </ion-content> </body> </html>

controller.js

https://riptutorial.com/zh-TW/home 32

angular.module('starter') .controller('ImageController', function($scope, $cordovaDevice, $cordovaFile, $ionicPlatform, $cordovaEmailComposer, $ionicActionSheet, ImageService, FileService) { $ionicPlatform.ready(function() { $scope.images = FileService.images(); $scope.$apply(); }); $scope.addMedia = function() { $scope.hideSheet = $ionicActionSheet.show({ buttons: [ { text: 'Take photo' }, { text: 'Photo from library' }, { text: '<b ng-disabled="user.length<1">Delete</b>', type: 'input type="file"'} ], titleText: 'Add images', cancelText: 'Cancel', buttonClicked: function(index) { $scope.addImage(index); } }); } $scope.addImage = function(type) { $scope.hideSheet(); ImageService.handleMediaDialog(type).then(function() { $scope.$apply(); }); } $scope.sendEmail = function() { if ($scope.images != null && $scope.images.length > 0) { var mailImages = []; var savedImages = $scope.images; for (var i = 0; i < savedImages.length; i++) { mailImages.push('base64:attachment'+i+'.jpg//' + savedImages[i]); } $scope.openMailComposer(mailImages); } } $scope.openMailComposer = function(attachments) { var bodyText = '<html><h2>My Images</h2></html>'; var email = { to: '', attachments: attachments, subject: 'Devdactic Images', body: bodyText, isHtml: true }; $cordovaEmailComposer.open(email, function(){ console.log('email view dismissed'); }, this); } });

https://riptutorial.com/zh-TW/home 33

service.js

angular.module('starter') .factory('FileService', function() { var images; var IMAGE_STORAGE_KEY = 'dav-images'; function getImages() { var img = window.localStorage.getItem(IMAGE_STORAGE_KEY); if (img) { images = JSON.parse(img); } else { images = []; } return images; }; function addImage(img) { images.push(img); window.localStorage.setItem(IMAGE_STORAGE_KEY, JSON.stringify(images)); }; return { storeImage: addImage, images: getImages } }) .factory('ImageService', function($cordovaCamera, FileService, $q, $cordovaFile) { function optionsForType(type) { var source; switch (type) { case 0: source = Camera.PictureSourceType.CAMERA; break; case 1: source = Camera.PictureSourceType.PHOTOLIBRARY; break; } return { quality: 90, destinationType: Camera.DestinationType.DATA_URL, sourceType: source, allowEdit: false, encodingType: Camera.EncodingType.JPEG, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: false, correctOrientation:true }; } function saveMedia(type) { return $q(function(resolve, reject) { var options = optionsForType(type); $cordovaCamera.getPicture(options).then(function(imageBase64) { FileService.storeImage(imageBase64); }); })

https://riptutorial.com/zh-TW/home 34

} return { handleMediaDialog: saveMedia } });

Ionic 3

CordovaIonic Native

$ ionic cordova plugin add cordova-plugin-camera $ npm install --save @ionic-native/camera

app.module.ts

import { Camera } from '@ionic-native/camera'; .......... @NgModule({ declarations: [ MyApp ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), ........... ], bootstrap: [IonicApp], entryComponents: [ MyApp ], providers: [ StatusBar, SplashScreen, Camera, {provide: ErrorHandler, useClass: IonicErrorHandler}, .......... ] }) export class AppModule {}

Ionic 3Actionpage.ts

import { Camera, CameraOptions } from '@ionic-native/camera'; ......... export class YourPage { private base64:any; constructor(private camera: Camera,private actionsheetCtrl: ActionSheetController) { } cameragalleryfun(){ let actionSheet = this.actionsheetCtrl.create({ title: 'Camera-Gallery', cssClass: 'action-sheets-basic-page',

https://riptutorial.com/zh-TW/home 35

buttons: [ { text: 'Camera', icon: 'camera', handler: () => { //console.log('Camera'); const options: CameraOptions = { quality: 60, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, sourceType : this.camera.PictureSourceType.CAMERA, targetWidth: 500, saveToPhotoAlbum: false, correctOrientation:true } this.camera.getPicture(options).then((imageData) => { this.base64 = 'data:image/jpeg;base64,' + imageData; }, (err) => { // Handle error }); } }, { text: 'Gallery', icon: 'images', handler: () => { //console.log('Gallery'); const options: CameraOptions = { quality: 60, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, sourceType : this.camera.PictureSourceType.PHOTOLIBRARY, targetWidth: 500, saveToPhotoAlbum: false, correctOrientation:true } this.camera.getPicture(options).then((imageData) => { this.base64 = 'data:image/jpeg;base64,' + imageData; }, (err) => { // Handle error }); } }, { text: 'Cancel', role: 'cancel', // will always sort to be on the bottom icon: 'close', handler: () => { //console.log('Cancel clicked'); } } ] }); actionSheet.present(); } }

https://riptutorial.com/zh-TW/home 36

cameragalleryfunbase64。。 https //github.com/apache/cordova-plugin-camera

Ionic https://riptutorial.com/zh-TW/ionic-framework/topic/7086/ionic

https://riptutorial.com/zh-TW/home 37

14: Ionic

Examples

macOS

APK

APK。

ionic build --release android

APK。 keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

my-release-key 。•

alias_name 。•

APK

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore HelloWorld-release-unsigned.apk alias_name

my-release-key 。•

apkHelloWorld-release-unsigned 。 ionic-project/platforms/android/build/outputs/apk 。•

alias_name。•

APK

zipalign -v 4 HelloWorld-release-unsigned.apk HelloWorld.apk

/Users/username/Library/Android/sdk/build-tools/XXX/zipalign•apkHelloWorld-release-unsigned 。 ionic-project/platforms/android/build/outputs/apk 。•

apkHelloWorld.apk 。Google Play。•

Ionic https://riptutorial.com/zh-TW/ionic-framework/topic/7755/ionic

https://riptutorial.com/zh-TW/home 38

15: AngularJS

IonicJavascript AngularJS。。

Examples

HTML。IonicHTML。Ionic。

<ion-checkbox ng-model="checkbox">Label</ion-checkbox>

<ion-radio ng-model="radio" ng-value="'radiovalue'">Value</ion-radio>

<ion-toggle ng-model="toggle" toggle-class="toggle-calm">Toggle</ion-toggle>

Ionic。<script>。templatesmodal-template.htmlhtml。fromTemplateUrl。

HTML

<ion-modal-view> <ion-header-bar> <h1>Modal title</h1> </ion-header-bar> <ion-content> <p>Modal content</p> </ion-content> </ion-modal-view>

$ionicModal.fromTemplateUrl('/templates/modal-template.html', { scope: $scope, animation: 'slide-in-up' }).then(function(modal) { $scope.modal = modal; });

$scope.modal.show();

$scope.modal.hide();

$scope.modal.remove();

https://riptutorial.com/zh-TW/home 39

16: CLI

Cordova CLICordova / Ionic。Hook。

Node.jsJavascript。

after_build after_compile after_docs after_emulate after_platform_add after_platform_rm after_platform_ls after_plugin_add after_plugin_ls after_plugin_rm after_plugin_search after_prepare after_run after_serve before_build before_compile before_docs before_emulate before_platform_add before_platform_rm before_platform_ls before_plugin_add before_plugin_ls before_plugin_rm before_plugin_search before_prepare before_run before_serve pre_package/ <-- Applicable to Windows 8 and Windows Phone only. This hook is deprecated.

<hook>config.xml<hook>

<hook type="after_build" src="scripts/appAfterBuild.js" />

plugin.xml <hook>

<hook type="after_build" src="scripts/afterBuild.js" />

before_plugin_install after_plugin_install before_plugin_uninstall/。

https://riptutorial.com/zh-TW/home 41

root/hooksconfig.xmlplugin.xmlhook。root/hooks。

Cordova Hooks。

Examples

jshintbefore_prepareJavascript

#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var jshint = require('jshint').JSHINT; var async = require('async'); var foldersToProcess = [ 'js' ]; foldersToProcess.forEach(function(folder) { processFiles("www/" + folder); }); function processFiles(dir, callback) { var errorCount = 0; fs.readdir(dir, function(err, list) { if (err) { console.log('processFiles err: ' + err); return; } async.eachSeries(list, function(file, innercallback) { file = dir + '/' + file; fs.stat(file, function(err, stat) { if (!stat.isDirectory()) { if (path.extname(file) === ".js") { lintFile(file, function(hasError) { if (hasError) { errorCount++; } innercallback(); }); } else { innercallback(); } } else { processFiles(file); } }); }, function(error) { if (errorCount > 0) { process.exit(1); } }); }); } function lintFile(file, callback) { console.log("Linting " + file);

https://riptutorial.com/zh-TW/home 42

fs.readFile(file, function(err, data) { if (err) { console.log('Error: ' + err); return; } if (jshint(data.toString())) { console.log('File ' + file + ' has no errors.'); console.log('-----------------------------------------'); callback(false); } else { console.error('Errors in file ' + file); var out = jshint.data(), errors = out.errors; for (var j = 0; j < errors.length; j++) { console.error(errors[j].line + ':' + errors[j].character + ' -> ' + errors[j].reason + ' -> ' + errors[j].evidence); } console.error('-----------------------------------------'); setTimeout(function() { callback(true); }, 10); } }); }

CLI https://riptutorial.com/zh-TW/ionic-framework/topic/6520/cli

https://riptutorial.com/zh-TW/home 43

17: CSS

IonicCSS。。CSSIonic。

Ionic CSS。。。ionic.css CSS。IonicSass_variables.scss。

ionic setup sassIonicSASS。

Ionic CSS http //ionicframework.com/docs/components/

Examples

Ionicrow。。。。

.COL-10 10

.COL-20 20

.COL-25 25

.COL-33 33.3333

.COL-50 50

.COL-67 66.6666

.COL-75 75

.COL-80 80

.COL-90 90

100.。

<div class="row"> <div class="col col-50">.col.col-50</div> <div class="col">.col</div> <div class="col">.col</div> </div> <div class="row"> <div class="col col-75">.col.col-75</div> <div class="col">.col</div> </div> <div class="row"> <div class="col">.col</div>

https://riptutorial.com/zh-TW/home 44

<div class="col col-75">.col.col-75</div> </div> <div class="row"> <div class="col">.col</div> <div class="col">.col</div> </div>

col-offset-<value>。。

<div class="row"> <div class="col col-33 col-offset-33">.col</div> <div class="col">.col</div> </div>

col-<align_value>。

<div class="row"> <div class="col col-top">.col</div> <div class="col col-center">.col</div> <div class="col col-bottom">.col</div> <div class="col">1<br>2<br>3<br>4</div> </div>

。。。

<div class="row row-center"> <div class="col">.col</div> <div class="col">.col</div> <div class="col">.col</div> <div class="col">1<br>2<br>3<br>4</div> </div>

。。

.responsive-SM

.responsive-MD

.responsive-LG

<div class="row responsive-sm"> <div class="col">.col</div> <div class="col">.col</div>

https://riptutorial.com/zh-TW/home 45

<div class="col">.col</div> <div class="col">.col</div> </div>

/。

。 IonicCSS。HTMLion-list。。

CSS

<ul class="list"> <li class="item"></li> </ul>

<div class="list"> <a class="item" href="#"> List item </a> <div class="item item-divider"> Divider that looks a bit different from items </div> <a class="item" href="#"> Another list item </a> </div>

<div class="list"> <a class="item item-icon-left" href="#"> <i class="icon ion-trash-b"></i> List item with a trashcan icon on the left </a> </div>

<div class="list"> <a class="item item-icon-left item-icon-right" href="#"> <i class="icon ion-trash-b"></i> List item with a trashcan icon on the left and a briefcase icon on the right <i class="icon ion-briefcase"></i> </a> </div>

<div class="list"> <div class="item item-button-right"> Item with a button on the right that has a clock icon in it <button class="button button-positive"> <i class="icon ion-clock"></i> </button> </div> </div>

。 Ionic。

Ionic。Ionic。

https://riptutorial.com/zh-TW/home 46

<ion-list> <ion-checkbox ng-model="choice1">Choice 1</ion-checkbox> <ion-checkbox ng-model="choice2">Choice 2</ion-checkbox> </ion-list>

Ionic CSS。ionic.cssCSS。SASSIonicSASSionic setup sass。

。 button-<phrase>。

<button class="button button-positive"> button-positive </button> <button class="button button-calm"> button-calm </button> <button class="button button-balanced"> button-balanced </button>

CSS

<element>-light•

<element>-stable•

<element>-positive•

<element>-calm•

<element>-balanced•

<element>-energized•

<element>-assertive•

<element>-royal•

<element>-dark•

<span class="badge badge-positive">Positive badge</span>

CSS https://riptutorial.com/zh-TW/ionic-framework/topic/6689/css

https://riptutorial.com/zh-TW/home 47

18: ionic.io

Examples

Ionic。

Ionic PlatformIonic Framework 。

1.

。 。

Ionic。。

2.

Ionic 。Web

WebIonic Platform。

$ ionic add ionic-platform-web-client

IDAPI。ionic io init。

$ ionic io init

。app idapiIonic Platform 。

Ionic 。

3. Ionic Platform

/••••

Analytics•

ionic.io https://riptutorial.com/zh-TW/ionic-framework/topic/3622/-ionic-io-

https://riptutorial.com/zh-TW/home 48

19: Http

Examples

n

HTML

<li class="item" ng-repeat="schedule in Schedules | filter:scheduleSearch | limitTo:numberOfItemsToDisplay"> Display some data </li> <ion-infinite-scroll on-infinite="addMoreItem()" ng-if="Schedules.length > numberOfItemsToDisplay"></ion-infinite-scroll>

$scope.numberOfItemsToDisplay = 10; // Use it with limit to in ng-repeat $scope.addMoreItem = function(done) { if ($scope.Schedules.length > $scope.numberOfItemsToDisplay) $scope.numberOfItemsToDisplay += 10; // load number of more items $scope.$broadcast('scroll.infiniteScrollComplete') }

addMoreItem10。

Http https://riptutorial.com/zh-TW/ionic-framework/topic/9490/-http-

https://riptutorial.com/zh-TW/home 49

S. No

Contributors

1Akshay Khale, Andrea Macchieraldo, Community, Devid Farinelli, Ian Pinto, leetheguy, Lightbeard, Mazz, Newton Joshua, the_mahasagar

2 “”“” Nikola

3Ionic - jshintgulp-jshint

Akilan Arasu, Ian Pinto, Sumama Waheed, thepio

4 Ionicons thepio

5 YeomanIonic Cloud Newton Joshua

6 Ionic A-Droid Tech, Ian Pinto

7 Ionic AppA-Droid Tech, Gerard Cuadras, Ian Pinto, Ketan Akbari, olivier, Raymond Ativie

8 Ionic App A-Droid Tech, Ian Pinto, Ketan Akbari, maninak

9 A-Droid Tech

10 IonicEcmaScript 6 Nikola

11 Ionic Nikola

12 Ionic Nikola

13 Ionic Pritish, sonu

14 Ionic Gerard Cuadras

15 AngularJS thepio

16 CLI thepio

17 CSS thepio

18 ionic.io Tomislav Stankovic

19 Http SANAT

https://riptutorial.com/zh-TW/home 50