如何使用TypeScript定义控制器?

时间:2015-05-27 12:14:57

标签: angularjs typescript

如何使用TypeScript定义控制器。就像现在它在角度js中,但我想为类型脚本更改它。因此可以快速检索数据。

function CustomerCtrl($scope, $http, $templateCache){

    $scope.search = function(search)
    {
        debugger;
        var Search = {
            AccountId: search.AccountId,
            checkActiveOnly: search.checkActiveOnly,
            checkParentsOnly: search.checkParentsOnly,
            listCustomerType: search.listCustomerType
        };
        $scope.customer = [];
        $scope.ticket = [];
        $scope.services = [];
        $http.put('<%=ResolveUrl("API/Search/PutDoSearch")%>', Search).
            success(function(data, status, headers, config) {
                debugger;
                $scope.cust_File = data[0].customers;
                $scope.ticket_file = data[0].tickets;
                $scope.service_file = data[0].services;
            }).
            error(function(data, status)
            {
                console.log("Request Failed");
            });
    }
}

4 个答案:

答案 0 :(得分:17)

有两种不同的方法可以解决这个问题:

  • 仍在使用$ scope
  • 使用controllerAs(推荐
  

使用$ scope

class CustomCtrl{
    static $inject = ['$scope', '$http', '$templateCache'];
    constructor (
            private $scope,
            private $http,
            private $templateCache
    ){
        $scope.search = this.search;
    }

    private search (search) {
        debugger;
        var Search = {
            AccountId: search.AccountId,
            checkActiveOnly: search.checkActiveOnly,
            checkParentsOnly: search.checkParentsOnly,
            listCustomerType: search.listCustomerType
        };
        this.$scope.customer = [];
        this.$scope.ticket = [];
        this.$scope.services = [];
        this.$http.put('<%=ResolveUrl("API/Search/PutDoSearch")%>', Search).
                success((data, status, headers, config) => {
                    debugger;
                    this.$scope.cust_File = data[0].customers;
                    this.$scope.ticket_file = data[0].tickets;
                    this.$scope.service_file = data[0].services;
                }).
                error((data, status) => {
                    console.log("Request Failed");
                });

    }
}
  

使用controllerAs

class CustomCtrl{
    public customer;
    public ticket;
    public services;
    public cust_File;
    public ticket_file;
    public service_file;

    static $inject = ['$scope', '$http', '$templateCache'];
    constructor (
            private $http,
            private $templateCache
    ){}

    private search (search) {
        debugger;
        var Search = {
            AccountId: search.AccountId,
            checkActiveOnly: search.checkActiveOnly,
            checkParentsOnly: search.checkParentsOnly,
            listCustomerType: search.listCustomerType
        };
        this.customer = [];
        this.ticket = [];
        this.services = [];
        this.$http.put('<%=ResolveUrl("API/Search/PutDoSearch")%>', Search).
                success((data, status, headers, config) => {
                    debugger;
                    this.cust_File = data[0].customers;
                    this.ticket_file = data[0].tickets;
                    this.service_file = data[0].services;
                }).
                error((data, status) => {
                    console.log("Request Failed");
                });

    }
}

如果您从$ scope切换到controller,您的视图将从以下更改:

<div ng-controller="CustomCtrl">
  <span>{{customer}}</span>
</div>

为:

<div ng-controller="CustomCtrl as custom">
  <span>{{custom.customer}}</span>
</div>

其中custom是控制器的表示,因此您明确告诉您在标记中绑定了什么。

注意 $ inject是一种方法,可以提供有关在运行时注入控制器的依赖项的信息,即使代码已经缩小(字符串不会缩小)

答案 1 :(得分:14)

我决定用工作示例添加另一个答案。这是非常简化的版本,但应该向我们显示所有基本的 TypeScript angularJS

a working plunker

这将是我们data.json扮演服务器的角色。

{
  "a": "Customer AAA",
  "b": "Customer BBB",
  "c": "Customer DDD",
  "d": "Customer DDD",
  "Default": "Not found"
}

这将是我们的起始模块MainApp.js

var app = angular.module('MainApp', [
  'CustomerSearch'
  ]);

angular.module('CustomerSearch',[])

所以稍后我们可以使用模块CustomerSearch。这将是我们的index.html

<!DOCTYPE html>
<html ng-app="MainApp" ng-strict-di>

  <head>
    <title>my app</title>
    <script data-require="angular.js@*"
            src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular.js"
            ></script>

    <script src="MainApp.js"></script>
    <script src="CustomerSearch.dirc.js"></script>
  </head> 

  <body>    
    <customer-search></customer-search> // our directive
  </body> 

</html>

现在,我们将看到1)指令的声明,2)范围,3)控制器。这一切都可以在一个文件中(检查here)。让我们观察该文件的所有三个部分CustomerSearch.dirc.js (它是CustomerSearch.dirc。 ts ..但是对于我遵守的plunker而言)

1)获取对上面声明的模块'CustomerSearch'的引用并声明directive

/// <reference path="../scripts/angularjs/angular.d.ts" />
module CustomerSearch
{
    var app = angular.module('CustomerSearch');

    export class CustomerSearchDirective implements ng.IDirective
    {
        public restrict: string = "E";
        public replace: boolean = true;
        public template: string = "<div>" +
            "<input ng-model=\"SearchedValue\" />" +
            "<button ng-click=\"Ctrl.Search()\" >Search</button>" +
            "<p> for searched value <b>{{SearchedValue}}</b> " +
            " we found: <i>{{FoundResult}}</i></p>" +
            "</div>";
        public controller: string = 'CustomerSearchCtrl';
        public controllerAs: string = 'Ctrl';
        public scope = {};
    }

    app.directive("customerSearch", [() => new CustomerSearch.CustomerSearchDirective()]);

该指令在TypeScript中声明,并立即注入我们的模块

现在,我们声明一个范围用作Controller中的强类型对象:

    export interface ICustomerSearchScope  extends ng.IScope
    {
        SearchedValue: string;
        FoundResult: string;
        Ctrl: CustomerSearchCtrl;
    }

现在我们可以声明简单的控制器

    export class CustomerSearchCtrl
    {
        static $inject = ["$scope", "$http"];
        constructor(protected $scope: CustomerSearch.ICustomerSearchScope,
            protected $http: ng.IHttpService)
        {
            // todo
        }
        public Search(): void
        {
            this.$http
                .get("data.json")
                .then((response: ng.IHttpPromiseCallbackArg<any>) =>
                {
                    var data = response.data;
                    this.$scope.FoundResult = data[this.$scope.SearchedValue]
                        || data["Default"];
                });
        }
    }
    app.controller('CustomerSearchCtrl',  CustomerSearch.CustomerSearchCtrl);
}

action here

中观察所有内容

答案 2 :(得分:5)

还有更多要改进(例如,不要$ scope.search,但是Ctrl.search),但其中一种方法可能是:

首先,我们创建模块MyModule并定义一个新的$ scope - ICustomer Scope

module MyModule
{
    export interface ICustomerScope extends ng.IScope
    {
        search: (search: any) => void;
        customer: any[];
        ticket: any[];
        services: any[];

        cust_File: any[];
        ticket_file: any[];
        service_file: any[];
    }

接下来是控制器,稍后将注入角度模块。它确实使用上面定义的ICustomerScope

    export class CustomerCtrl
    {
        static $inject = ['$scope', '$http', '$templateCache'];

        constructor(protected $scope: ICustomerScope,
            protected $http: ng.IHttpService,
            protected $templateCache: ng.ITemplateCacheService)
        {
            $scope.search = this.search;
        }
        public search = (search: any) => 
        {
            debugger;
            var Search = {
                AccountId: search.AccountId,
                checkActiveOnly: search.checkActiveOnly,
                checkParentsOnly: search.checkParentsOnly,
                listCustomerType: search.listCustomerType
            };

            this.$scope.customer = [];
            this.$scope.ticket = [];
            this.$scope.services = [];

            var url = "someUrl"; // '<%=ResolveUrl("API/Search/PutDoSearch")%>'
            this.$http.put(url, Search).
                success((data, status, headers, config) =>
                {
                    debugger;
                    this.$scope.cust_File = data[0].customers;
                    this.$scope.ticket_file = data[0].tickets;
                    this.$scope.service_file = data[0].services;
                }).
                error((data, status) =>
                {
                    console.log("Request Failed");
                });
        }
    }

现在我们继续 - 我们得到模块的引用,并注册控制器:CustomerCtrl

    var app = angular.module("MyControllerModule");    

    app.controller("CustomerCtrl", MyModule.CustomerCtrl);
}

现在我们的控制器可以使用,将与原始相同。但可以使用并声明 $scope.methods()

代替的公共行动

答案 3 :(得分:0)

现在我们将看到一个基本示例,其中我们必须使用一种方法创建模块和控制器。要从Typescript开始,我们需要在项目中添加以下文件。不要考虑参考路径​​,只需从列表中找到文件名。

<script type="text/javascript" src="scripts/angular.js"></script>
<script type="text/javascript" src="scripts/angular-route.js"></script>
<script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="scripts/bootstrap.js"></script>

如果Visual Studio中没有,请从以下链接安装Typescript https://www.microsoft.com/en-us/download/details.aspx?id=48593

完成下载上面的输入文件后,将其添加到项目中。

/// <reference path="../scripts/typings/angularjs/angular.d.ts" />
/// <reference path="../scripts/typings/angularjs/angular-route.d.ts" />

现在创建一个打字稿文件app.ts并在前两行添加上述参考,以便在编码时获得智能感知。

请参阅以下链接以获取更多详细信息

https://angular2js.blogspot.in/2016/06/create-sample-application-in-angular-js.html