javascript - 如何将 angularJS 应用程序转换为 angular

标签 javascript angularjs angular typescript angular-controller

我目前在 AngularJS ( https://next.plnkr.co/edit/qpyvZuvI8vw8q6on?open=lib%2Fscript.js&preview ) 中定义了一个简单的搜索功能,但我希望将此功能迁移到现有的 Angular 应用程序中。我创建了一个新的 Angular 应用程序并将 View 移动到 app.component.html

  <head>
    <script src="./script.js"></script>
  </head>

  <h1> Search Feature </h1>

  <body ng-app="search" ng-cloak>
     <div id="content" ng-controller="MainCtrl">
        <input type='text' ng-model='searchText' placeholder=" Enter Query Here  " />  
          <ul>
            <li class="angular-with-newlines" ng-repeat="course in courses | filter:searchText"> 
              {{course.course_number}}: {{course.title}}
              <button ng-click="course.showDesc=!course.showDesc">See More</button> 
              <div ng-if="course.showDesc"> Description: {{course.description}} </div>
         </li>
      </ul>
    </div>
  </body>

然后我将 Controller 代码移动到名为 script.js 的 javascript 文件中

import angular from 'angular';

angular.module('search', []).controller('MainCtrl', function($scope) {

  $scope.courses = [
        {
            id: 1,
      course_number: '54 Mathematics',
      title: 'Linear Algebra and Differential Equations',
      description: 'Basic linear algebra; matrix arithmetic and determinants. Vector spaces; inner product as spaces.',
      keywords: 'determinants, linear, equations, inner, basic, spaces, partial, order'
        },
        {
            id: 2,
      course_number: '110 Mathematics',
      title: 'Linear Algebra',
      description: "Matrices, vector spaces, linear transformations, inner products, determinants.",
      keywords: "determinants, forms, products, eigenvectors, linear"
        },
        {
           id: 3,
      course_number: '89A Statistics',
      title: 'Linear Algebra for Data Science',
      description: 'An introduction to linear algebra for data science.',
      keywords: 'ranking, prob, network, document, algebra, basics, model, matrices,'
        }

    ];
});

但是,我无法访问 Controller 中定义的任何数据,并且应用程序无法运行。我是网络开发的新手,所以这行不通吗,因为我需要将我的 javascript 代码转换为 typescript ?或者我是否需要以某种方式以不同的方式导入我的代码?

欢迎任何意见!谢谢你!

最佳答案

我需要学习一些 Angular,因此我尝试将其转化为学习成果。一步一步:

  1. 创建新项目 ng new test
  2. angular 中有管道函数,但没有管道过滤器,因此我们必须创建一个。 (CD测试)ng generate pipe search (我通过列出所有可生成的东西发现了这一点 ng generate --help
  3. 经过一些搜索,我了解到要使用“ng-model”,您需要将“FormsModule”添加到您的应用程序中。在 app.module.ts 中:import { FormsModule } from "@angular/forms";并更新@NgModule 导入:... imports: [ BrowserModule, FormsModule ], ... .
  4. 已更新 app.component.html使用我们的模板:

<div id="content"> <input type='text' [(ngModel)]='searchText' placeholder=" Enter Query Here" /> <ul> <li class="angular-with-newlines" *ngFor="let course of courses | Search:searchText"> {{course.course_number}}: {{course.title}} <button (click)="course.showDesc=!course.showDesc">See More</button> <div *ngIf="course.showDesc"> Description: {{course.description}} </div> </li> </ul> </div>

如果您知道旧模板的工作原理,那么我认为这些更改是不言自明的。进行了一些研究,但几乎所有内容都与 AngularJS 等效,并且仅对语法进行了一些更改。

  1. 还有 Controller 。没有更多的范围,只需在 Controller 中直接声明一个变量。当然还要添加搜索输入模型:

import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent { title = "app"; searchText = "Math"; // Just a default value courses = [{ id: 1, course_number: ...}, ...]; // Snip for readability }

  1. 最后实现我们的搜索过滤器。您需要在此处进行最多的工作(如果您无论如何都想完全模仿旧过滤器的话。

搜索.pipe.ts:

import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
  name: "Search",
  pure: false
})
export class SearchPipe implements PipeTransform {
  transform(items: any[], searchValue: string, filter: Object): any {
    return items.filter(item => {
      return item.title.indexOf(searchValue) > -1 ||
             item.course_number.indexOf(searchValue) > -1;
    });
  }
}

我使用 indexOf 和 es6 过滤器来创建一些简单的东西 - 这里只查看两个字段并且不区分大小写。我必须设置 purefalse让它正确更新。这对我来说表明管道可能不是做事的最佳方式。也许由模型更改(带去抖动)触发的 Controller 功能并创建结果数组会是一个更好的主意。

附加说明:使用 NgModel 可能有点矫枉过正,因为它以两种方式(从 Controller 到模板以及从模板到 Controller )绑定(bind)一个值,但我们从不更改该值(除了设置默认值), 所以跳过 ngModel 并使用 (change)="doSearch()"会少一个进口,也许更清洁,但我想模块化不如过滤器。

关于javascript - 如何将 angularJS 应用程序转换为 angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50979617/

相关文章:

javascript - new Date(2014,1,1) 使用 momentJS 转换为 2 月 1 日

javascript - 在 Google Chrome 中重新启用 document.execCommand ("cut")

JavaScript 对象具有具有特定正则表达式模式的键

javascript - 获取 sibling 的值(value) - extjs

html - 尝试使用 AngularJS 将编辑后的图像保存到我的本地计算机

javascript - 类型 'Subscription' 缺少类型 'Observable<StringMap<any>>' 的以下属性

javascript - 创建指令时不显示背景图像

javascript - 如何获取我的 Web 应用程序的实时数据?

带有 ng-template 的 Angular mat-tree

html - Angular 4 + Primeng(数据表): custom scrollHeight property