angular手机应用_灵活且易于维护的Laravel + Angular材质应用

编程知识 更新时间:2023-04-28 10:46:32

angular手机应用

In this article, we’re going to set up a Laravel API with Angular Material for the front end. We’re also going to follow best practices that will help us scale with the number of developers working on the project and the complexity behind it. Most tutorials cover this topic from another perspective – they completely forget about scaling. While this tutorial is not targeted at small todo apps, it is extremely helpful if you’re planning to work with other developers on a big project.

在本文中,我们将为前端设置一个带有Angular Material的Laravel API。 我们还将遵循最佳实践,这将帮助我们扩大从事该项目的开发人员的数量及其背后的复杂性。 大多数教程从另一个角度介绍了此主题-他们完全忘记了扩展。 虽然本教程并非针对小型的待办事项应用程序,但是如果您打算与其他开发人员合作进行大型项目,则本教程将非常有用。

Here’s a demo built with Laravel and Angular Material.

这是一个使用Laravel和Angular Material构建的演示 。

设置Laravel (Setting up Laravel)

建立专案 (Creating a project)

We’re going to start by pulling in the latest Laravel – 5.1 at the time of writing.

在撰写本文时,我们将从引入最新的Laravel 5.1开始。

composer create-project laravel/laravel myapp --prefer-dist

配置环境 (Configuring the environment)

All the subsequent commands will be ran inside the myapp directory. Throughout the remainder of this tutorial, we’ll assume you’re running a Linux environment if you’re following along. If you aren’t you’re encouraged to install Homestead Improved as a virtual Linux environment in which to follow along.

所有后续命令将在myapp目录中运行。 在本教程的其余部分中,如果您遵循以下步骤,我们将假定您正在运行Linux环境。 如果不是这样,建议您将Homestead Improvement安装为可跟随的虚拟Linux环境。

cd myapp

Next, we’re going to update our .env file with the database connection credentials:

接下来,我们将使用数据库连接凭据更新.env文件:

DB_HOST=localhost
DB_DATABASE=your-db-name
DB_USERNAME=your-username
DB_PASSWORD=your-password

Once your app has been configured, you should see the Laravel 5 greeting page.

配置好应用程序后,您应该会看到Laravel 5问候页面。

调试栏 (Debugbar)

Laravel debug bar is one of the most useful Laravel packages.

Laravel调试栏是最有用的Laravel软件包之一。

Debugbar makes it easy to debug any of the following:

Debugbar使调试以下任何一项变得容易:

  • exceptions

    例外情况
  • views

    意见
  • messages

    讯息
  • queries

    查询
  • mails

    邮件
  • auth

    认证
  • routes

    路线
  • ajax

    阿贾克斯
  • and more

    和更多

So let’s go ahead and install it using composer

因此,让我们继续使用composer进行安装

composer require barryvdh/laravel-debugbar

Next, we need to open config/app.php and:

接下来,我们需要打开config/app.php并:

  • add Barryvdh\Debugbar\ServiceProvider::class, to the list of providers

    Barryvdh\Debugbar\ServiceProvider::class,添加到providers列表中

  • add 'Debugbar' => Barryvdh\Debugbar\Facade::class, to the list of aliases

    'Debugbar' => Barryvdh\Debugbar\Facade::class,aliases列表中

Refresh the page and you should see debugbar at the bottom of the page!

刷新页面,您将在页面底部看到debugbar栏!

Debugbar runs automatically if you have the APP_DEBUG flag enabled in your .env file.

如果您在.env文件中启用了APP_DEBUG标志,则Debugbar将自动运行。

构建自动化 (Build automation)

Laravel’s Elixir is a layer on top of gulp that makes it easier to write gulp tasks.

Laravel的药剂是在之上的一层gulp ,使得它更容易编写一口任务。

建立 (Setup)

We’ll start by installing gulp globally. Note that you need nodeJS installed for this section.

我们将从全局安装gulp开始。 请注意,此部分需要安装nodeJS。

npm install -g gulp

and then we need to grab a few packages that will make our lives easier, so replace your package.json with the following:

然后我们需要获取一些可以使我们的生活更轻松的软件包,因此,用以下代码替换您的package.json

{
  "dependencies": {
    "gulp-concat": "^2.6.0",
    "gulp-concat-sourcemap": "^1.3.1",
    "gulp-filter": "^1.0.2",
    "gulp-if": "^1.2.5",
    "gulp-jshint": "^1.9.0",
    "gulp-minify-css": "^0.3.11",
    "gulp-ng-annotate": "^1",
    "gulp-notify": "^2.0.0",
    "gulp-sourcemaps": "^1",
    "gulp-uglify": "^1",
    "jshint-stylish": "^2",
    "laravel-elixir": "^3.0.0",
    "laravel-elixir-livereload": "^1.1.1",
    "main-bower-files": "^2.1.0"
  },
  "devDependencies": {
    "gulp": "^3.9.0"
  }
}

Then install these packages.

然后安装这些软件包。

npm install

管理前端依赖项 (Managing front-end dependencies)

I like to use Bower because of its flat dependency tree, but that’s really up to your preference. You can use npm, requirejs or just the plain old browse-to-url-and-download-and-then-manually-check-for-updates.

我喜欢使用Bower,因为它具有扁平的依赖关系树 ,但这确实取决于您的偏好。 您可以使用npm,requirejs或仅使用普通的旧版本浏览至URL并下载,然后手动检查更新

Let’s install bower globally.

让我们在全球范围内安装凉亭。

npm install -g bower

Then add this line to .gitignore:

然后将此行添加到.gitignore

/bower_components

/bower_components

and run bower init to create a new bower.json file which will be committed in the repository.

并运行bower init来创建一个新的bower.json文件,该文件将在存储库中提交。

按功能文件夹 (Folder by Feature)

Then, we want to choose a location for Angular within our Laravel folder.

然后,我们想在Laravel文件夹中为Angular选择一个位置。

Most people prefer to add it to resources/js but since I prefer to have a folder by feature architecture, we’re going to create an angular folder at the root level.

大多数人都喜欢将其添加到resources/js但是由于我更喜欢按要素体系结构创建文件夹,因此我们将在根级别创建一个angular文件夹。

I chose this setup because we want it to be able to scale with the number of developers and with the business complexity behind it.

我选择此设置是因为我们希望它能够随着开发人员数量以及背后的业务复杂性进行扩展。

A few months from now, we’re going to have a folder for every feature. Here’s an example of the folders that we are going to have inside angular/app:

从现在开始的几个月后,我们将为每个功能提供一个文件夹。 这是我们将在angular/app包含的文件夹的示例:

  • header

    标头

    • header.html

      header.html
    • header.js

      header.js
    • header.less

      无标题
  • login

    登录

    • login.html

      login.html
    • login.js

      login.js
    • login.less

      无登录
    • service.js

      service.js
  • landing

    降落
  • users

    使用者
  • change_password

    更改密码
  • reset_password

    重设密码
  • list_items

    list_items
  • add_item

    新增项目
  • item_details

    item_details

It’s much easier to fix bugs in the list_items page. We just have to open the list_items folder where we find all the related files for this feature:

list_items页面中修复错误要容易得多。 我们只需要打开list_items文件夹,即可在其中找到此功能的所有相关文件:

  • templates

    范本
  • Less files

    文件少
  • Angular controller(s)

    角度控制器
  • Angular service(s).

    角度服务。

Compare this to having to open a folder for each of these files when debugging a single feature.

与此相比,调试单个功能时必须为每个文件打开一个文件夹。

So let’s go ahead and create the following folders:

因此,让我们继续创建以下文件夹:

  • angular

    angular

  • angular/app

    angular/app

  • angular/services

    angular/services

  • angular/filters

    angular/filters

  • angular/directives

    angular/directives

  • angular/config

    angular/config

药剂配置 (Elixir configuration)

Now we need to configure elixir to compile a js/vendor.js and a css/vendor.css file from the bower_components folder.

现在,我们需要配置elixir以从bower_components文件夹中编译js/vendor.jscss/vendor.css文件。

Then we need to run our angular folder through the elixir angular task, which does the following:

然后,我们需要通过长生不老药的angular任务来运行角度文件夹,该任务执行以下操作:

  • concatenates our app files into public/js/app.js

    将我们的应用程序文件连接到public/js/app.js

  • validates with jshint (if the .jshintrc file is available). If the file is available, it won’t recompile our source code if your code does not pass validation.

    使用jshint进行验证(如果.jshintrc文件可用)。 如果该文件可用,则如果您的代码未通过验证,它将不会重新编译我们的源代码。

  • automatic dependency annotation using ng-annotate

    使用ng-annotate自动依赖注释

We need to compile our less files. If you’re using Sass, you probably know how to make it work for Sass.

我们需要编译较少的文件。 如果您使用的是Sass,则可能知道如何使其适用于Sass。

We also need to copy our views from within the angular directory to the public directory.

我们还需要将视图从angular目录内复制到public目录。

Finally, we are going to set up livereload. Soft reloads are used for CSS, meaning that a newer version of your css will be injected without reloading the page.

最后,我们将设置livereload。 软重新加载用于CSS,这意味着将在不重新加载页面的情况下注入新版本CSS。

Let’s open gulpfile.js and replace the sample Elixir function call with the following:

让我们打开gulpfile.js并将示例Elixir函数调用替换为以下内容:

var elixir = require('laravel-elixir');
require('./tasks/angular.task.js');
require('./tasks/bower.task.js');
require('laravel-elixir-livereload');

elixir(function(mix){
    mix
        .bower()
        .angular('./angular/')
        .less('./angular/**/*.less', 'public/css')
        .copy('./angular/app/**/*.html', 'public/views/app/')
        .copy('./angular/directives/**/*.html', 'public/views/directives/')
        .copy('./angular/dialogs/**/*.html', 'public/views/dialogs/')
        .livereload([
            'public/js/vendor.js',
            'public/js/app.js',
            'public/css/vendor.css',
            'public/css/app.css',
            'public/views/**/*.html'
        ], {liveCSS: true});
});

If you noticed, I’m loading a couple of custom tasks, so you just need to create the tasks folder at the root directory of the project and create these 2 files:

如果您注意到了,我正在加载几个自定义任务,因此您只需要在项目的根目录中创建tasks文件夹并创建这两个文件:

tasks/angular.task.js

任务/ angular.task.js

/*Elixir Task
*copyrights to https://github/HRcc/laravel-elixir-angular
*/
var gulp = require('gulp');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var ngAnnotate = require('gulp-ng-annotate');
var notify = require('gulp-notify');
var gulpif = require('gulp-if');

var Elixir = require('laravel-elixir');

var Task = Elixir.Task;

Elixir.extend('angular', function(src, output, outputFilename) {

    var baseDir = src || Elixir.config.assetsPath + '/angular/';

    new Task('angular in ' + baseDir, function() {
        // Main file has to be included first.
        return gulp.src([baseDir + "main.js", baseDir + "**/*.js"])
            .pipe(jshint())
            .pipe(jshint.reporter(stylish))
            //.pipe(jshint.reporter('fail')).on('error', onError) //enable this if you want to force jshint to validate
            .pipe(gulpif(! config.production, sourcemaps.init()))
            .pipe(concat(outputFilename || 'app.js'))
            .pipe(ngAnnotate())
            .pipe(gulpif(config.production, uglify()))
            .pipe(gulpif(! config.production, sourcemaps.write()))
            .pipe(gulp.dest(output || config.js.outputFolder))
            .pipe(notify({
                title: 'Laravel Elixir',
                subtitle: 'Angular Compiled!',
                icon: __dirname + '/../node_modules/laravel-elixir/icons/laravel.png',
                message: ' '
            }));
    }).watch(baseDir + '/**/*.js');

});

tasks/bower.task.js

任务/ower.task.js

/*Elixir Task for bower
* Upgraded from https://github/ansata-biz/laravel-elixir-bower
*/
var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');
var filter = require('gulp-filter');
var notify = require('gulp-notify');
var minify = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var concat_sm = require('gulp-concat-sourcemap');
var concat = require('gulp-concat');
var gulpIf = require('gulp-if');

var Elixir = require('laravel-elixir');

var Task = Elixir.Task;

Elixir.extend('bower', function(jsOutputFile, jsOutputFolder, cssOutputFile, cssOutputFolder) {

    var cssFile = cssOutputFile || 'vendor.css';
    var jsFile = jsOutputFile || 'vendor.js';

    if (!Elixir.config.production){
        concat = concat_sm;
    }

    var onError = function (err) {
        notify.onError({
            title: "Laravel Elixir",
            subtitle: "Bower Files Compilation Failed!",
            message: "Error: <%= error.message %>",
            icon: __dirname + '/../node_modules/laravel-elixir/icons/fail.png'
        })(err);
        this.emit('end');
    };

    new Task('bower-js', function() {
        return gulp.src(mainBowerFiles())
            .on('error', onError)
            .pipe(filter('**/*.js'))
            .pipe(concat(jsFile, {sourcesContent: true}))
            .pipe(gulpIf(Elixir.config.production, uglify()))
            .pipe(gulp.dest(jsOutputFolder || Elixir.config.js.outputFolder))
            .pipe(notify({
                title: 'Laravel Elixir',
                subtitle: 'Javascript Bower Files Imported!',
                icon: __dirname + '/../node_modules/laravel-elixir/icons/laravel.png',
                message: ' '
            }));
    }).watch('bower.json');


    new Task('bower-css', function(){
        return gulp.src(mainBowerFiles())
            .on('error', onError)
            .pipe(filter('**/*.css'))
            .pipe(concat(cssFile))
            .pipe(gulpIf(config.production, minify()))
            .pipe(gulp.dest(cssOutputFolder || config.css.outputFolder))
            .pipe(notify({
                title: 'Laravel Elixir',
                subtitle: 'CSS Bower Files Imported!',
                icon: __dirname + '/../node_modules/laravel-elixir/icons/laravel.png',
                message: ' '
            }));
    }).watch('bower.json');

});

These 2 gulp tasks might look a bit complex, but you don’t have to worry about that. You’re here to speed up your development process rather than wasting time setting up build tools.

这两个gulp任务可能看起来有些复杂,但是您不必为此担心。 您来这里是为了加快开发过程,而不是浪费时间设置构建工具。

The reason why I’m not using some of the available node modules that are available online, is because, at the time of writing, they are slow and often limited in terms of functionality. Enjoy!

我之所以不使用某些在线可用的可用节点模块,是因为在编写本文时,它们很慢,并且在功能方面常常受到限制。 请享用!

设置AngularJS (Setting up AngularJS)

安装 (Installation)

Let’s get started by downloading the latest version of Angular 1

让我们开始下载最新版本的Angular 1

bower install angular#1 --save

Don’t forget the --save flag because we want this to be saved in bower.json

不要忘记--save标志,因为我们希望将其保存在bower.json

We can now run gulp && gulp watch.

现在,我们可以运行gulp && gulp watch

配置主模块 (Configuring Main Module)

Let’s start by configuring angular/main.js

让我们从配置angular/main.js

(function(){
"use strict";

var app = angular.module('app',
        [
        'app.controllers',
        'app.filters',
        'app.services',
        'app.directives',
        'app.routes',
        'app.config'
        ]);

    angular.module('app.routes', []);
    angular.module('app.controllers', []);
    angular.module('app.filters', []);
    angular.module('app.services', []);
    angular.module('app.directives', []);
    angular.module('app.config', []);
    })();

桥接Laravel和Angular (Bridging Laravel & Angular)

服务应用 (Serving the App)

We need to create a new controller using artisan.

我们需要使用工匠创建一个新的控制器。

php artisan make:controller AngularController --plain
AngularController.php


public function serveApp(){
    return view('index');
}

and then replace the existing Route::get('/', ...) in routes.php with the following:

然后取代现有的Route::get('/', ...)routes.php有以下几点:

Route::get('/', 'AngularController@serveApp');

This seems useless at first, but I like to keep the logic outside the Routes file, so I prefer not to have closures there. Eventually, we’re going to use this controller for other methods, like the unsupported browser page.

起初这似乎没有用,但是我希望将逻辑保留在Routes文件之外,因此我不希望在此处关闭。 最终,我们将将此控制器用于其他方法,例如不受支持的浏览器页面。

Then, we need to create the view resources/views/index.blade.php and add this HTML:

然后,我们需要创建视图resources/views/index.blade.php并添加以下HTML:

<html ng-app="app">
<head>
    <link rel="stylesheet" href="/css/vendor.css">
    <link rel="stylesheet" href="/css/app.css">
</head>
<body>

    <md-button class="md-raised md-primary">Welcome to Angular Material</md-button>

    <script src="/js/vendor.js"></script>
    <script src="/js/app.js"></script>
</body>
</html>

不支持的浏览器 (Unsupported Browser)

Angular Material is targeted at evergreen browsers, so we need to add a page for unsupported ones ( IE <= 10 ).

Angular Material是针对常绿浏览器的,因此我们需要为不支持的浏览器添加页面(IE <= 10)。

We start by adding the following conditional comment in the <head> of our index.blade.php view:

我们首先在index.blade.php视图的<head>中添加以下条件注释:

<!--[if lte IE 10]>
    <script type="text/javascript">document.location.href ='/unsupported-browser'</script>
    <![endif]-->

This will redirect the user with an unsupported browser to /unsupported-browser, a route which we should handle in routes.php:

这会将使用不受支持的浏览器的用户重定向到/unsupported-browser ,这是我们应该在routes.php处理的路由:

Route::get('/unsupported-browser', 'AngularController@unsupported');

Then, inside AngularController we create the unsupported method:

然后,在AngularController内部,我们创建unsupported方法:

public function unsupported(){
    return view('unsupported');
}

Finally, we create the unsupported.blade.php view and output a message telling the user that they needs to upgrade to a modern browser.

最后,我们创建unsupported.blade.php视图并输出一条消息,告知用户他们需要升级到现代浏览器。

引入角材料 (Pulling in Angular Material)

Angular Material is an implementation of Material Design in Angular.js. It provides a set of reusable, well-tested, and accessible UI components based on the Material Design system.

Angular Material是Angular.js中Material Design的实现。 它提供了一组基于Material Design系统的可重用,经过良好测试和可访问的UI组件。

安装 (Installation)

First we pull Angular Material using Bower:

首先,我们使用Bower拉角材料:

bower install angular-material --save

Then, we add the ngMaterial module to the app.controllers and app.config modules:

然后,我们将ngMaterial模块添加到app.controllersapp.config模块中:

angular.module('app.controllers', ['ngMaterial']);
angular.module('app.config', ['ngMaterial']);

Finally, we re-run gulp watch.

最后,我们重新运行gulp watch

自定义主题 (Custom theming)

You probably love the feel that Angular Material gives to your app, but you’re worried that it’ll look exactly like Angular Material.

您可能喜欢Angular Material给您的应用程序带来的感觉,但您担心它看起来会与Angular Material完全一样。

We’ll want to apply some branding guidelines to the theme, which is why we need to create a new config provider for Angular Material which allows us to specify the 3 main colors for our theme:

我们将对主题应用一些商标准则,这就是为什么我们需要为Angular Material创建一个新的配置提供程序,该提供程序允许我们为主题指定3种主要颜色:

/angular/config/theme.js:


(function(){
    "use strict";

    angular.module('app.config').config( function($mdThemingProvider) {
        /* For more info, visit https://material.angularjs/#/Theming/01_introduction */
        $mdThemingProvider.theme('default')
        .primaryPalette('teal')
        .accentPalette('cyan')
        .warnPalette('red');
    });

})();

设置UI路由器 (Setting up ui-router)

ui-router is the de-facto solution to flexible routing with nested views.

ui-router是使用嵌套视图进行灵活路由的实际解决方案。

安装 (Installation)

Let’s start by pulling that in using bower:

让我们开始使用Bower:

bower install  ui-router --save

Then, add the ui.router module to the app.routes and app.controllers modules:

然后,将ui.router模块添加到app.routesapp.controllers模块中:

angular.module('app.routes', ['ui.router']);
angular.module('app.controllers', ['ngMaterial', 'ui.router']);

Then, we re-run gulp watch.

然后,我们重新运行gulp watch

配置路由 (Configuring routes)

Now we need to set up our routes file. Let’s go ahead and create angular/routes.js

现在我们需要设置路由文件。 让我们继续创建angular/routes.js

(function(){
    "use strict";

    angular.module('app.routes').config( function($stateProvider, $urlRouterProvider ) {

        var getView = function( viewName ){
            return '/views/app/' + viewName + '/' + viewName + '.html';
        };

        $urlRouterProvider.otherwise('/');

        $stateProvider
        .state('landing', {
            url: '/',
            views: {
                main: {
                    templateUrl: getView('landing')
                }
            }
        }).state('login', {
            url: '/login',
            views: {
                main: {
                    templateUrl: getView('login')
                },
                footer: {
                    templateUrl: getView('footer')
                }
            }
        });

    } );
})();

We created 2 routes, one for the Landing page and the other for the Login page. Notice how we have multiple named views. We need to add that to our main view, inside the <body>:

我们创建了2条路线,一条用于“着陆”页面,另一条用于“登录”页面。 注意我们如何有多个命名视图。 我们需要在<body>内部将其添加到我们的主视图中:

<div ui-view="main"></div>
<div ui-view="footer"></div>

We then create the following folders and files inside angular/app:

然后,我们在angular/app创建以下文件夹和文件:

  • landing/landing.html with the output Landing view

    Landing view landing/landing.html和输出Landing view

  • login/login.html with the output Login view

    login/login.html和输出“ Login view

  • footer/footer.html with the output Footer view

    footer/footer.html和输出Footer view

Now, whenever you need to add a new page, you just have to add a new .state().

现在,每当需要添加新页面时,只需添加一个新的.state()

设置矩形 (Setting up Restangular)

Restangular is an AngularJS service that simplifies common ajax calls to a RESTful API.

Restangular是AngularJS服务,可简化对RESTful API的常见ajax调用。

安装 (Installation)

Restangular is a perfect fit with our Laravel API.

Restangular非常适合我们的Laravel API。

Let’s grab the latest version of Restangular by running the following:

让我们通过运行以下命令来获取最新版本的Restangular:

bower install restangular --save

Then, add the restangular module to the app.controllers module:

然后,将restangular模块添加到app.controllers模块:

angular/main.js:

angular.module('app.controllers', ['ngMaterial', 'ui.router', 'restangular']);

Then, re-run gulp watch.

然后,重新运行gulp watch

Let’s set up a sample API endpoint.

让我们设置一个示例API端点。

php artisan make:controller DataController --plain
DataController.php:

public function index(){
    return ['data', 'here'];
}
app\Http\routes.php:

Route::get('/data', 'DataController@index');

Sample Usage:

用法示例:

Restangular.all('data').doGET().then(function(response){
    window.console.log(response);
});

吐司 (Toast)

A toast provides simple feedback about an operation in a small popup.

吐司可在一个小弹出窗口中提供有关操作的简单反馈。

Since we’re going to use toasts a lot in our application, we’re going to create a toast service angular/services/toast.js

由于我们将在应用程序中大量使用Toast,因此我们将创建Toast服务angular/services/toast.js

(function(){
    "use strict";

    angular.module("app.services").factory('ToastService', function( $mdToast ){

        var delay = 6000,
        position = 'top right',
        action = 'OK';

        return {
            show: function(content) {
                return $mdToast.show(
                    $mdToast.simple()
                    .content(content)
                    .position(position)
                    .action(action)
                    .hideDelay(delay)
                    );
            }
        };
    });
})();

And now here’s how we can use it in our app:

现在,我们介​​绍了如何在应用程序中使用它:

(function(){
    "use strict";

    angular.module('app.controllers').controller('TestCtrl', function( ToastService ){
                    ToastService.show('User added successfully');
            };

        });

})();

对话方块 (Dialogs)

Dialogs are one of the most useful features available in Angular Material. They’re very similar to Modals in Twitter Bootstrap.

对话框是Angular Material中可用的最有用的功能之一。 它们与Twitter Bootstrap中的Modals非常相似。

Dialogs are a key component in Single Page Apps, that’s why we’re going to write a powerful dialog service /angular/services/dialog.js

对话框是Single Page Apps中的关键组件,因此我们要编写功能强大的对话框服务/angular/services/dialog.js

(function(){
    "use strict";

    angular.module("app.services").factory('DialogService', function( $mdDialog ){

        return {
            fromTemplate: function( template, $scope ) {

                var options = {
                    templateUrl: '/views/dialogs/' + template + '/' + template + '.html'
                };

                if ( $scope ){
                    options.scope = $scope.$new();
                }

                return $mdDialog.show(options);
            },

            hide: function(){
                return $mdDialog.hide();
            },

            alert: function(title, content){
                $mdDialog.show(
                    $mdDialog.alert()
                    .title(title)
                    .content(content)
                    .ok('Ok')
                    );
            }
        };
    });
})();

We created 3 methods inside this service:

我们在此服务内创建了3种方法:

  • alert(title, content) allows us to display a dialog with a title and a message. Useful for error and success messages

    alert(title, content)允许我们显示一个带有标题和消息的对话框。 对于错误和成功消息很有用

  • hide() hides the dialog

    hide()隐藏对话框

  • fromTemplate(template, $scope) creates a dialog from a template stored in /angular/dialogs/. Useful for Login, Reigster, etc. dialogs. You can create your own component inside the /angular/dialogs/ directory using the same folder by feature approach. You can also pass $scope to the dialog, which will give you access to the $parent scope from within the dialog’s controller.

    fromTemplate(template, $scope)/angular/dialogs/存储的模板创建一个对话框。 对于登录,Reigster等对话框很有用。 您可以通过功能相同的文件夹在/angular/dialogs/目录中创建自己的组件。 您还可以将$scope传递给对话框,这将使您可以从对话框的控制器内访问$parent范围。

We just need to fix the Elixir configuration to watch and copy the /angular/dialogs folder:

我们只需要修复Elixir配置即可观察和复制/angular/dialogs文件夹:

.copy('angular/dialogs/**/*.html', 'public/views/dialogs/');

And now here’s how we can use it in our app:

现在,我们介​​绍了如何在应用程序中使用它:

(function (){
    "use strict";

    angular.module('app.controllers').controller('DialogTestCtrl', function ($scope, DialogService){


            $scope.addUser = function(){
                return DialogService.fromTemplate('add_user', $scope);
            };

            $scope.success = function(){
                return DialogService.alert('Success', 'User created successfully!');
            };


        });

})();

部署方式 (Deployment)

Here’s a plain bash script that we’re going to use for deployment. You can save it as deploy.sh.

这是我们将用于部署的普通bash脚本。 您可以将其另存为deploy.sh

You’d just need to prepend it with an ssh command to your server ssh@your-domain.

您只需要在服务器ssh@your-domain前面加上ssh命令即可。

php artisan route:clear
php artisan config:clear
git pull
php artisan migrate
composer install
php artisan route:cache
php artisan config:cache
php artisan optimize

The first two commands clear the route and configuration cache, which will then be generated again after pulling the new code. This will greatly improve the performance of your app when running in production.

前两个命令清除路由和配置缓存,然后在提取新代码后再次生成路由和配置缓存。 在生产环境中运行时,这将大大提高应用程序的性能。

Don’t forget that any configuration/routing change you make will not take effect until you clear the cache again.

不要忘记,您所做的任何配置/路由更改都不会生效,直到您再次清除缓存。

代码质量 (Code Quality)

Enforcing code quality helps the maintenance of big projects. You don’t want to end up with a terrible code base a few months from now. This is completely optional, but I’d recommend you set up some automated code quality tools.

加强代码质量有助于维护大型项目。 从现在开始几个月后,您都不想得到一个糟糕的代码库。 这是完全可选的,但是我建议您设置一些自动化的代码质量工具。

We’re going to start by installing the necessary node modules:

我们将从安装必要的节点模块开始:

npm install -g jshint jscs

编辑器配置 (EditorConfig)

EditorConfig helps us maintain a consistent coding style between different editors and IDEs. This is especially useful when you have many developers/contributors working on the same project.

EditorConfig帮助我们在不同的编辑器和IDE之间保持一致的编码风格。 当您有许多开发人员/贡献者在同一个项目上工作时,此功能特别有用。

You don’t want someone to push code with spaces instead of tabs, or vice versa, CRLF as line endings instead of LF, or vice versa.

您不希望有人用空格而不是制表符来推送代码,反之亦然,CRLF作为行尾而不是LF来反之亦然。

Let’s create the.editorconfig file at the root level. Feel free to switch between CRLF and LF, tabs and spaces, etc.. it all depends on your coding style.

让我们在根级别创建.editorconfig文件。 可以在CRLF和LF,制表符和空格等之间自由切换。这完全取决于您的编码样式。

root = true

[*]
insert_final_newline = false
charset = utf-8
end_of_line = lf

[*.{js,html}]
indent_size = 4
indent_style = tab
trim_trailing_whitespace = true

[{package.json,bower.json,.jscs.json}]
indent_style = space
indent_size = 2

[*.sh]
end_of_line = lf

Depending on your code editor, you might need to download a plugin for editorConfig.

根据您的代码编辑器,您可能需要下载 editorConfig的插件。

This is also convenient when you are working on more than 1 project using the same text editor and each project has different coding style guidelines.

当您使用同一个文本编辑器处理多个项目时,并且每个项目都有不同的编码样式准则时,这也很方便。

捷迅 (JSHINT)

Jshint is a Javascript code quality tool that helps to detect errors and potential problems in Javascript code.

Jshint是Javascript代码质量工具,可帮助检测Javascript代码中的错误和潜在问题。

It also enforces coding conventions on your team.

它还在您的团队上执行编码约定。

We need to create a .jshintrc file at the root level of the project. You can browse the available options for jshint here. Note that when you add a .jshintrc file, the angular task we have in our gulpfile will not recompile our code if it doesn’t validate according to jshint.

我们需要在项目的根目录下创建一个.jshintrc文件。 您可以在此处浏览jshint的可用选项。 请注意,当您添加.jshintrc文件时,如果它未根据jshint进行验证,则在gulpfile中具有的angular任务将不会重新编译我们的代码。

Here’s a recommended jshintrc for our scenario. Feel free to modify it according to your coding style.

这是针对我们的方案的推荐的jshintrc 。 随时根据您的编码样式对其进行修改。

{
  "browser": true,
  "bitwise": true,
  "immed": true,
  "newcap": false,
  "noarg": true,
  "noempty": true,
  "nonew": true,
  "maxlen": 140,
  "boss": true,
  "eqnull": true,
  "eqeqeq": true,
  "expr": true,
  "strict": true,
  "loopfunc": true,
  "sub": true,
  "undef": true,
  "globals": {
    "angular": false,
    "describe": false,
    "it": false,
    "expect": false,
    "beforeEach": false,
    "afterEach": false,
    "module": false,
    "inject": false
  }
}

JSCS (JSCS)

JSCS is a code style linter for programmatically enforcing your style guide.

JSCS是用于以编程方式实施样式指南的代码样式标记。

We’re going to create a .jscs.json file at the root level. Feel free to modify it depending on your style.

我们将在根级别创建一个.jscs.json文件。 随时根据您的样式进行修改。

{
  "requireCurlyBraces": [
    "if",
    "else",
    "for",
    "while",
    "do"
  ],
  "requireSpaceAfterKeywords": [
    "if",
    "for",
    "while",
    "do",
    "switch",
    "return"
  ],
  "disallowSpacesInFunctionExpression": {
    "beforeOpeningRoundBrace": true
  },
  "disallowTrailingWhitespace": true,
  "disallowMixedSpacesAndTabs": true,
  "requireMultipleVarDecl": true,
  "requireSpacesInsideObjectBrackets": "all",
  "requireSpaceBeforeBinaryOperators": [
    "+",
    "-",
    "/",
    "*",
    "=",
    "==",
    "===",
    "!=",
    "!=="
  ],
  "disallowSpaceAfterPrefixUnaryOperators": [
    "++",
    "--",
    "+",
    "-"
  ],
  "disallowSpaceBeforePostfixUnaryOperators": [
    "++",
    "--"
  ],
  "disallowKeywords": [
    "with"
  ],
  "disallowKeywordsOnNewLine": [
    "else"
  ],
  "excludeFiles": ["node_modules/**"]
}

PHPCS (PHPCS)

Just like jshint, we need to be able to enforce code cleanliness and consistency for our PHP files.

就像jshint一样,我们需要能够对PHP文件强制执行代码整洁性和一致性。

Let’s start by installing phpcs globally:

让我们从全局安装phpcs开始:

composer global require "squizlabs/php_codesniffer=*"

Now we can use the following command to check the app folder:

现在我们可以使用以下命令来检查app文件夹:

phpcs --standard=psr2 app/

The cool thing here is that we can use PSR2 as a coding standard which is used by Laravel, so we don’t have to set up a custom configuration file.

这里很酷的事情是我们可以将PSR2用作Laravel使用的编码标准,因此我们不必设置自定义配置文件。

吊钩 (Git hooks)

Jshint and jscs are great tools, but they need to be automatically enforced or else we’ll forget to lint our code.

Jshint和jscs是很棒的工具,但是它们需要自动执行,否则我们会忘记整理代码。

You can optionally install the corresponding linter plugins for your text editor or IDE, but one of the recommended ways of doing it would be to run these linters as part of your git commit process.

您可以选择为文本编辑器或IDE安装相应的linter插件,但是推荐的一种实现方法是在git commit过程中运行这些linter。

Create .git/hooks/pre-commit if it does not exist and add the following:

如果.git/hooks/pre-commit不存在,请创建并添加以下内容:

#!/bin/sh
jscs angular/**/*.js
jshint angular/**/*.js
phpcs --standard=psr2 app/
exec 1>&2

Then run chmod +x .git/hooks/pre-commit.

然后运行chmod +x .git/hooks/pre-commit

Don’t forget to add this for each developer who joins your team, and every time someone pushes, they’ll be automatically warned of possible issues.

不要忘了为加入您团队的每个开发人员添加此代码,每当有人按下按钮时,系统都会自动警告他们可能出现的问题。

结论 (Conclusion)

This article helped us set up a scalable Laravel and Angular Material app. You can also grab the source code of this tutorial on github: laravel5-angular-material-starter. If you’ve been using Angular with Bootstrap, I’d recommend you give Angular Material a try. Do you have any questions? I’d love to know what you think. Just let me know in the comments!

本文帮助我们建立了一个可扩展的Laravel和Angular Material应用程序。 您也可以在github上获取本教程的源代码: laravel5-angular-material-starter 。 如果您一直在将Angular与Bootstrap结合使用,建议您尝试一下Angular Material。 你有任何问题吗? 我很想知道你的想法。 请在评论中让我知道!

翻译自: https://www.sitepoint/flexible-and-easily-maintainable-laravel-angular-material-apps/

angular手机应用

更多推荐

angular手机应用_灵活且易于维护的Laravel + Angular材质应用

本文发布于:2023-04-21 06:56:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/77de34cb3a193624069a973647b66192.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:材质   灵活   手机   angular   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 92596文章数
  • 23582阅读数
  • 0评论数