如何使用TypeScript定义控制器?

Shi*_* JA 15 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");
            });
    }
}
Run Code Online (Sandbox Code Playgroud)

Bro*_*cco 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");
                });

    }
}
Run Code Online (Sandbox Code Playgroud)

使用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");
                });

    }
}
Run Code Online (Sandbox Code Playgroud)

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

<div ng-controller="CustomCtrl">
  <span>{{customer}}</span>
</div>
Run Code Online (Sandbox Code Playgroud)

至:

<div ng-controller="CustomCtrl as custom">
  <span>{{custom.customer}}</span>
</div>
Run Code Online (Sandbox Code Playgroud)

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

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

  • @RadimKöhler我拿了你的$ $ inject`并在我的答案中加入了 (2认同)

Rad*_*ler 15

我决定用工作示例添加另一个答案.它是非常简化的版本,但应该显示所有基本的如何对我们TypeScriptangularJS.

一个工作的plunker

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

{
  "a": "Customer AAA",
  "b": "Customer BBB",
  "c": "Customer DDD",
  "d": "Customer DDD",
  "Default": "Not found"
}
Run Code Online (Sandbox Code Playgroud)

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

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

angular.module('CustomerSearch',[])
Run Code Online (Sandbox Code Playgroud)

所以稍后我们可以使用模块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>
Run Code Online (Sandbox Code Playgroud)

现在,我们将看到1)指令的声明,2)范围,3)控制器.这一切都可以在一个文件中(在这里查看).让我们观察到文件的所有三个部分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()]);
Run Code Online (Sandbox Code Playgroud)

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

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

    export interface ICustomerSearchScope  extends ng.IScope
    {
        SearchedValue: string;
        FoundResult: string;
        Ctrl: CustomerSearchCtrl;
    }
Run Code Online (Sandbox Code Playgroud)

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

    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);
}
Run Code Online (Sandbox Code Playgroud)

观察这里的所有动作


Rad*_*ler 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[];
    }
Run Code Online (Sandbox Code Playgroud)

接下来是控制器,稍后将注入角度模块.它确实使用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");
                });
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

    app.controller("CustomerCtrl", MyModule.CustomerCtrl);
}
Run Code Online (Sandbox Code Playgroud)

现在我们的控制器可以使用,将与原始相同.但也可以使用和声明的公共行为,而不是$scope.methods()