ionic4创建应用命令_使用AngularJS和Ionic创建您的第一个移动应用

ionic4创建应用命令

The Scotchmas Day 4 giveaway can be found at the end of this article.

在本文的末尾可以找到Scotchmas Day 4赠品。

In the past years, making a mobile app involved being good with the native language you are creating an app for. That means Objective C for iOS, Java for Android, and C# for Windows Phone. That is so demoralizing to have to learn all those technologies.

在过去的几年中,使移动应用程序与您要为其创建应用程序的本国语言相称。 这意味着iOS的Objective C,Android的Java和Windows Phone的C#。 如此令人沮丧,必须学习所有这些技术。

My dreams of being a mobile app developer became a reality after I realized I could actually create mobile apps using the skills I had that were web technologies.

当我意识到我可以使用Web技术创建移动应用程序后,成为移动应用程序开发人员的梦想就变成了现实。

Cordova is a game changer. With it you can target multiple platforms with one code base. All you need to learn is the usual HTML, CSS and JavaScript used for web development and by reading some Cordova docs, you are already to become a mobile developer.

科尔多瓦是改变游戏规则的人。 有了它,您可以使用一个代码库针对多个平台。 您需要学习的是用于Web开发的常规HTML,CSS和JavaScript,通过阅读一些Cordova文档,您已经成为一名移动开发人员。

离子到底是什么? (What Really is Ionic?)

Ionic is a front-end SDK for building cross-platform mobile apps. Built on top of Angular, Ionic also provides a platform for integrating services like push notifications and analytics.

Ionic是用于构建跨平台移动应用程序的前端SDK。 Ionic建立在Angular之上,还提供了一个平台,用于集成推送通知和分析等服务。

Ionic_Logo.svg

Ionic is not an alternative option to Cordova, but instead a UI library to make a better Cordova project. Ionic can be compared to a framework like Bootstrap or Foundation but this time for Mobile and not Web.

Ionic并不是Cordova的替代选项,而是一个UI库,可以使Cordova项目更好。 可以将Ionic与Bootstrap或Foundation之类的框架进行比较,但这一次是针对Mobile而非Web。

In this tutorial which has a nice demo, we will make a mobile app using Ionic framework and Cordova. I will also explain how to build mobile apps with Phonegap app so we won't have to bother with installing Platform SDKs.

在具有良好演示的本教程中,我们将使用Ionic框架和Cordova制作一个移动应用程序。 我还将说明如何使用Phonegap应用程序构建移动应用程序,这样我们就不必费心安装Platform SDK。

你应该知道什么 (What You Should Know)

Fortunately you just need to understand the basics of JavaScript and its popular library AngularJS. Ionic is completely made up of Angular directives and components and uses its popular ui router for SPA.

幸运的是,您只需要了解JavaScript的基础知识及其流行的库AngularJS 。 Ionic完全由Angular指令和组件组成,并将其流行的ui路由器用于SPA。

Currently, Ionic works with Angular 1.0, but the Ionic 2 Alpha that works with Angular 2 was announced.

目前,Ionic可与Angular 1.0一起使用,但已宣布可与Angular 2一起使用的Ionic 2 Alpha

安装与安装 (Setup and Installation)

These days it seems like everything now depends on Node to exist. Ionic and Cordova are not exceptions. Installing Cordova or Ionic requires Node and npm installed on your machine. Run the following command after installing Node if you haven't:

这些天似乎一切都取决于Node的存在。 离子性和科尔多瓦也不例外。 安装Cordova或Ionic需要在计算机上安装Node和npm。 如果尚未安装Node,请运行以下命令:

npm install -g cordova ionic

The -g flag installs both cordova and ionic globally so we can access it from any where in our machines. It also adds them to our PATH so it won't be a surprise to our CLI. To confirm installation:

-g标志全局安装了cordova和ionic,因此我们可以从计算机中的任何位置访问它。 它还会将它们添加到我们的PATH因此对于我们的CLI来说不会感到惊讶。 确认安装:

ioniv -v && cordova -v

创建一个项目 (Creating a Project)

A new project in ionic can be created using the ionic CLI command. It will scaffold the app's file and download it's dependencies. You can supply arguments to the CLI command to alter the type of template generated.

可以使用ionic CLI命令在ionic中创建一个新项目。 它将搭建应用程序的文件并下载其依赖项。 您可以为CLI命令提供参数,以更改生成的模板的类型。

ionic start {appname} {template}

That is the syntax for a new project in Ionic. The appname is any name of your choice and template is one of the Ionic supported template. It can also be a GitHub URL to a custom template.

这是Ionic中新项目的语法。 appname是您选择的任何名称, template是Ionic支持的模板之一。 它也可以是自定义模板的GitHub URL。

There is nothing wrong with tradition - let us create a Todo app to better see what Ionic is made of.

传统没有错-让我们创建一个Todo应用程序以更好地了解Ionic的构成。

制作Todo应用 (Making a Todo App)

We can go ahead and create an app as seen in the previous section. So as usual, pick your favorite spot on you machine and run:

我们可以继续创建一个应用程序,如上一节所述。 因此,像往常一样,在计算机上选择自己喜欢的位置并运行:

ionic start scotch-todo blank

We are using the blank template for simplicity in as much as we can use other types of templates like tabs, sidemenus, etc. The command will generate a new project for us and also install some dependencies.

为了简化起见,我们在使用blank模板的同时也使用了其他类型的模板,例如tabssidemenus等。该命令将为我们生成一个新项目并安装一些依赖项。

├── hooks          // custom cordova hooks to execute on specific commands
├── platforms      // iOS/Android specific builds will reside here
├── plugins        // where your cordova/ionic plugins will be installed
├── resources        // icon and splash screen
├── scss           // scss code, which will output to www/css/
|── www         // application - JS code and libs, CSS, images, etc.
     |---------css                 //customs styles
     |---------img               //app images
     |---------js                  //angular app and custom JS
     |---------lib                //third party libraries
     |---------index.html  //app master page        
├── bower.json     // bower dependencies
├── config.xml     // cordova configuration
├── gulpfile.js    // gulp tasks
├── ionic.project  // ionic configuration
├── package.json   // node dependencies

配置平台 (Configuring Platforms)

As we discussed, Cordova gives you the power to write once and run on many platforms (iOS, Android, Blackberry, Windows, etc) but you have to explicitly tell Cordova (with Ionic) which platform should be included in a given project. For our Todo app, we will be trying with two platforms (iOS and Android).

正如我们所讨论的,Cordova使您能够编写一次并在许多平台(iOS,Android,Blackberry,Windows等)上运行,但是您必须明确地告诉Cordova(使用Ionic)在给定的项目中应该包含哪个平台。 对于Todo应用程序,我们将尝试使用两个平台(iOS和Android)。

cd scotch-todo
ionic platform add ios
ionic platform add android

预览应用 (Previewing the App)

We can preview our app in the browser using Ionic. This is not recommended though (about that later) but we can use it to preview (not really test) our basic Todo application.

我们可以使用Ionic在浏览器中预览我们的应用程序。 虽然不建议这样做(稍后再介绍),但是我们可以使用它来预览(而不是真正测试)我们的基本Todo应用程序。

To see what our blank app looks like, run the below command in the CLI on the scotch-todo directory:

要查看空白应用程序的外观,请在scotch-todo目录的CLI中运行以下命令:

ionic serve

The command will open up a browser at http:localhost:8100. The browser screen is too large to preview a mobile app and for that reason, Ionic added --lab as an option to running the app in the browser so as to preview the app better as it would be seen in Android and iOS.

该命令将打开位于http:localhost:8100的浏览器。 浏览器屏幕太大,无法预览移动应用程序,因此,Ionic添加了--lab作为在浏览器中运行应用程序的选项,以便更好地预览应用程序,就像在Android和iOS中看到的那样。

ionic serve --lab

ionic-serve

建立真正的东西 (Building Out the Real Stuff)

Fine we have a good ionic app but then it is useless. We agreed on making a Todo app not a blank app so let us complete the deal.

很好,我们有一个好的离子应用程序,但是那没用。 我们同意将Todo应用制作为空白应用,因此让我们完成交易。

Ionic is a basically a SPA web app, we need a master index.html though we don't need routes as the Todo app is just a one view app.

Ionic基本上是一个SPA Web应用程序,尽管Todo应用程序只是一个视图应用程序,但我们不需要路由,但我们需要一个master index.html。

We should first update our app's www/index.html and www/js/app.js to make sure the structure looks like the one below.

我们应该首先更新应用程序的www/index.htmlwww/js/app.js ,以确保结构看起来像下面的结构。

www/index.html

www/index.html

<html>
  <head>
    <meta charset="utf-8">
    <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">
    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <!-- your app's js -->
  <body ng-app="scotch-todo">

    <ion-pane>
     <ion-header-bar class="bar-dark">
        <h1 class="title">Scotch-Todo</h1>
      </ion-header-bar>
      <ion-content>
      </ion-content>
    </ion-pane>
  </body>
</html>

www/js/app.js

www/js/app.js

//setup angular
var app = angular.module('scotch-todo', ['ionic']);

Ionic creates a bundle of Angular and required dependencies (angular-ui-router, angular-animate, angular-sanitize, etc) bundled in one file as ionic.bundle.js.

Ionic创建了一个Angular包和所需的依赖项(angular-ui-router,angular-animate,angular-sanitize等),捆绑为ionic.bundle.js文件。

Those are the files we will work with throughout this tutorial. Before continuing, let us define some tasks we need to complete in out app so we don't loose focus:

这些是我们在整个教程中将使用的文件。 在继续之前,让我们定义一些需要在应用程序内完成的任务,这样我们就不会失去重点:

  • Setup Local Storage service to store todo data

    设置本地存储服务以存储待办事项数据
  • Create a main controller to interact with our view

    创建一个main控制器来与我们的视图进行交互
  • Update our index.html to work with the controller

    更新我们的index.html以使用控制器

本地存储服务 (A Local Storage Service)

HTML 5 which is ionic's best friend comes with a lot of storage options. Local Storage is one of them and it suits our app more because of all the options provided, it has the ability to persist data even when the browser or app is closed.

HTML 5是ionic的最好朋友,它提供了许多存储选项。 本地存储就是其中之一,由于提供了所有选项,它更适合我们的应用程序,即使在关闭浏览器或应用程序的情况下,它也能够保留数据。

Angular on the other hand has a service written to wrap the Local Storage API and is available on GitHub as angular-local-storage. Fortunately, Ionic uses bower to manage dependencies so installing angular-local-storage takes this CLI command:

另一方面,Angular编写了用于包装Local Storage API的服务,并在GitHub上以angular-local-storage的形式提供 。 幸运的是,Ionic使用Bower来管理依赖项,因此安装angular-local-storage可以使用以下CLI命令:

bower install angular-local-storage --save

The command will download and add angular-local-storage to our app libraries. Just below where we added the ionic.bundle.js include angular-local-storage as seen below:

该命令将下载angular-local-storage并将其添加到我们的应用程序库。 在我们添加了ionic.bundle.js位置的正下方,包括angular-local-storage,如下所示:

<script src="lib/angular-local-storage/dist/angular-local-storage.js"></script>

Tell angular it is a dependency by injecting it in the angular app in the www/js/app/js file like this:

通过将其注入www/js/app/js文件中的angular应用程序,以告诉angular它是一个依赖项:

var app = angular.module('scotch-todo', ['ionic', 'LocalStorageModule']);

It is a good practice to add a prefix to our stored entities so as avoid being overwritten in future. Add a config angular block to set the Local Storage prefix

最好在存储的实体上添加前缀,以免将来被覆盖。 添加配置角度块以设置本地存储前缀

app.config(function (localStorageServiceProvider) {
    localStorageServiceProvider
      .setPrefix('scotch-todo');
  });

Let us leave it at that and continuing to the second item on our task - the controller.

让我们继续讨论,然后继续执行任务的第二项-控制器。

main控制器 (The main Controller)

Our controller will be serving as the middle man between our data (Local Storage) and the view (www/index.html). Let us first create a structure of the controller just below our config block in the www/js/app.js:

我们的控制器将充当我们的数据(本地存储)和视图( www/index.html )之间的中间人。 让我们首先在www/js/app.js中的config块下面创建控制器的结构:

app.controller('main', function ($scope, $ionicModal, localStorageService) { //store the entities name in a variable var taskData = 'task';

//initialize the tasks scope with empty array
$scope.tasks = [];

//initialize the task scope with empty object
$scope.task = {};

//configure the ionic modal before use
$ionicModal.fromTemplateUrl('new-task-modal.html', {
    scope: $scope,
    animation: 'slide-in-up'
}).then(function (modal) {
    $scope.newTaskModal = modal;
});

$scope.getTasks = function () {
    //fetches task from local storage
    ...
}
$scope.createTask = function () {
    //creates a new task
    ...
}
$scope.removeTask = function () {
    //removes a task
    ...
}
$scope.completeTask = function () {
    //updates a task as completed
    ...
}
})

Notice how we have injected localStorageService in the controller so as to help us interact with Local Storage from the controller. We also injected$ionicModal service to help us create tasks from a modal.

请注意我们如何将localStorageService注入控制器中,以帮助我们与控制器中的Local Storage进行交互。 我们还注入了$ionicModal服务,以帮助我们从模式中创建任务。

We also need to tell the index.html which controller to use and run getTasks() when the app starts by updating the body tag as shown:

我们还需要通过更新body标签来告诉index.html使用哪个控制器并在应用启动时运行getTasks() ,如下所示:

<body ng-app="scotch-todo" ng-controller="main" ng-init="getTasks()">
... 
</body>

We are making reasonable progress. Let us now implement those empty methods in the controller. We will start with the getTasks() which basically checks for tasks entity in the Local Storage and if it exists, fetch it.

我们正在取得合理的进展。 现在让我们在控制器中实现那些空方法。 我们将从getTasks()开始,该getTasks()基本上检查本地存储中的tasks实体,如果存在,则将其获取。

$scope.getTasks = function () {
          //fetches task from local storage
          if (localStorageService.get(taskData)) {
              $scope.tasks = localStorageService.get(taskData);
          } else {
              $scope.tasks = [];
          }
   }

Furthermore we can can create a new task by pushing a task object to the tasks array and updating the Local Storage with the tasks.

此外,我们可以通过将task对象推送到tasks数组并使用tasks更新本地存储来创建新tasks

$scope.createTask = function () {
          //creates a new task
          $scope.tasks.push($scope.task);
          localStorageService.set(taskData, $scope.tasks);
          $scope.task = {};
          //close new task modal
          $scope.newTaskModal.hide();
   }

To remove task we can now remove a task object from the task array and update the Local Storage.

要删除任务,我们现在可以从任务数组中删除任务对象并更新本地存储。

$scope.removeTask = function (index) {
          //removes a task
          $scope.tasks.splice(index, 1);
          localStorageService.set(taskData, $scope.tasks);
     }

Then to complete a task we find task from the array using its index, update it's completed value and update Local Storage.

然后,要完成任务,我们使用数组的索引从数组中查找任务,更新其完成值并更新本地存储。

$scope.completeTask = function (index) { 
 //updates a task as completed 
 if (index !== -1) {
  $scope.tasks[index].completed = true; 
 } 

  localStorageService.set(taskData, $scope.tasks); 
}

That is it! We can boast of a controller now. Let us not get too excited though because our view is waiting patiently to get a treat as we did to our controller.

这就对了! 我们现在可以夸耀控制器。 但是,让我们不要太兴奋,因为我们的观点正在耐心地等待我们对控制器的对待。

风景 (The View)

For a cleaner display of tasks, let us use ionic's card component for display of tasks. So right inside the <ion-content> tag (which is actually a directive) add the following block:

为了更清晰地显示任务,让我们使用离子卡组件显示任务。 因此,在<ion-content>标记(实际上是一个指令)的内部,添加以下块:

<div class="list card" ng-repeat="task in tasks track by $index">
            <div class="item item-divider">
                <span ng-bind="task.title"></span>
            </div>
            <div class="item item-body">
                <strong>Title: <span ng-bind="task.title"></span></strong>
                <p>
                    <span ng-bind="task.content"></span>
                </p>
            </div>

            <div class="item tabs tabs-secondary tabs-icon-left">
                <span class="item item-checkbox">
                    <label class="checkbox">
                        <input type="checkbox" ng-model="task.completed" ng-click="completeTask($index)">
                    </label>
                </span>
                <a class="tab-item assertive" ng-click="removeTask($index)">
                    <i class="icon ion-android-close"></i>
                </a>
            </div>

</div>

With that we have a list of tasks presented with cards in our view. Now to create a new task, we will use the modal which we already configured in our controller. We are tracking the array with a unique $index as it has none specified explicitly in the data source. Just before the body closing tag:

这样一来,我们就可以看到一张带有卡片的任务清单。 现在创建一个新任务,我们将使用已经在控制器中配置的模态。 我们正在使用唯一的$ index跟踪数组,因为该数组在数据源中未明确指定。 在body关闭标签之前:

<script id="new-task-modal.html" type="text/ng-template">
        <ion-modal-view>
            <ion-header-bar class="bar-dark">
                <h1 class="title">Create a new Task</h1>
                <button class="button button-icon" ng-click="closeTaskModal()">
                    <i class="icon ion-android-close"></i>
                </button>
            </ion-header-bar>
            <ion-content>
                <form ng-submit="createTask()">
                    <div class="list list-inset">
                        <label class="item item-input">
                            <input ng-model="task.title" type="text" placeholder="Task title">
                        </label>
                        <label class="item item-input">
                            <textarea ng-model="task.content" rows="5" placeholder="Task content"></textarea>
                        </label>
                        <ul class="list">
                            <li class="item item-toggle">
                                Completed?
                                <label class="toggle toggle-balanced">
                                    <input type="checkbox" ng-model="task.completed">
                                   <div class="track">
                                        <div class="handle"></div>
                                    </div>
                                </label>
                            </li>
                        </ul>
                        <button type="submit" class="button button-block button-positive">Create Task</button>
                    </div>
                </form>
            </ion-content>
        </ion-modal-view>
    </script>

Finally on the view, add a button to the ion-header-bar directive which will be used to open the modal.

最后,在视图上,向ion-header-bar指令添加一个按钮,该按钮将用于打开模式。

<ion-header-bar class="bar-dark">
    <h1 class="title">Scotch-Todo</h1>
    <!-- New Task button-->
    <button class="button button-icon" ng-click="openTaskModal()">
        <i class="icon ion-compose"></i>
    </button>
</ion-header-bar>

And that is it. That is our sweet simple Todo mobile app. On the other hand, I don't think we are comfortable testing an app that is supposed to run on a mobile app in a browser. Let's do something about that.

就是这样。 那就是我们最简单的Todo移动应用程序。 另一方面,我认为我们不愿意测试应该在浏览器中的移动应用程序上运行的应用程序。 让我们为此做些事情。

使用Phonegap App测试 (Testing with Phonegap App)

PhoneGap is a free and open source framework that allows you to create mobile apps using standardized web APIs for the platforms you care about.

PhoneGap是一个免费的开放源代码框架,可让您使用标准化Web API为您关心的平台创建移动应用程序。

PhoneGap just meets Cordova halfway to complement it where it is weak.

PhoneGap刚好在遇到弱点的地方与Cordova相遇。

One of those weaknesses is realtime testing while developing. With just Cordova we can only install platform SDKs, build our app once and test with the SDKs which might be slow and affects productivity.

这些弱点之一是开发时的实时测试。 仅使用Cordova,我们只能安装平台SDK,只构建一次应用程序,并使用这些SDK进行测试,这可能会很慢并且会影响生产率。

PhoneGap App lets us test our app in realtime while it is being built. No need for any sort of compiling or building before testing. All we need is a to place our machine and our device on the same network. First things first:

通过PhoneGap App ,我们可以在构建应用程序时实时对其进行测试。 测试之前无需任何形式的编译或构建。 我们所需要的只是将我们的机器和设备放置在同一网络上。 第一件事:

npm install -g phonegap

This will install the command line tool and give us access to use PhoneGap from the CLI. Next we need to install the app for our platform. I have an Android mobile device therefore am downloading from Play Store. You can see other platforms from the PhoneGap App website.

这将安装命令行工具,并使我们能够从CLI访问使用PhoneGap。 接下来,我们需要为平台安装该应用程序。 我有一个Android移动设备,因此正在从Play商店下载。 您可以从PhoneGap App网站上查看其他平台。

Finally on PhoneGap app, instead of using ionic serve on the Todo App, we will run with

最后在PhoneGap的应用程序,而不是使用ionic serve上的Todo应用程序,我们将与运行

phonegap serve

phone-gap-serve

Notice the I.P address because that is what we will use to talk to our mobile device.

请注意IP地址,因为这就是我们将用来与移动设备通信的地址。

Open the installed app on your device and replace the I.P address and port with the one supplied by PhoneGap CLI and tap connect. Below is a preview of the app:

打开设备上已安装的应用程序,然后用PhoneGap CLI提供的IP地址和端口替换IP地址和端口,然后点按“连接”。 以下是该应用的预览:

final-app-from-browser

final-mobile-create-task

Feel free to feel like the man (or woman). We did it! Our app is running live on our mobile device. You owe me a cup of coffee though.

感到自己像男人(或女人)。 我们做到了! 我们的应用程序正在我们的移动设备上实时运行。 你欠我一杯咖啡。

结论 (Conclusion)

I am so excited and proud to have completed this tutorial with you. As you can see, you didn't have to be a Java geek or Objective C nerd or C# professional to develop a mobile app, we just need to apply our Web development skills. I think that is amazing. This is just the beginning, expect more on Ionic from Scotch.

我很高兴和您一起完成本教程。 正如您所看到的,您不必是Java怪胎,Objective C专家或C#专业人士来开发移动应用程序,我们只需要应用我们的Web开发技能即可。 我认为这太神奇了。 这只是开始,请期待Scotch对Ionic的更多了解。

苏格兰赠品第四天 (Scotchmas Giveaway Day 4)

a Rafflecopter giveaway

Rafflecopter赠品

翻译自: https://scotch.io/tutorials/create-your-first-mobile-app-with-angularjs-and-ionic

ionic4创建应用命令

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值