如何使用 TypeScript 定义我的控制器? [英] How can I define my controller using TypeScript?

查看:21
本文介绍了如何使用 TypeScript 定义我的控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 TypeScript 定义我的控制器.现在它在 angular js 中,但我想将其更改为类型脚本.以便可以快速检索数据.

function CustomerCtrl($scope, $http, $templateCache){$scope.search = 函数(搜索){调试器;var 搜索 = {AccountId: 搜索.AccountId,checkActiveOnly: search.checkActiveOnly,checkParentsOnly:search.checkParentsOnly,listCustomerType: search.listCustomerType};$scope.customer = [];$scope.ticket = [];$scope.services = [];$http.put('<%=ResolveUrl("API/Search/PutDoSearch")%>', Search).成功(功能(数据,状态,标题,配置){调试器;$scope.cust_File = data[0].customers;$scope.ticket_file = data[0].tickets;$scope.service_file = data[0].services;}).错误(功能(数据,状态){console.log("请求失败");});}}

解决方案

我决定添加另一个答案,并附上工作示例.这是一个非常简化的版本,但应该向我们展示所有基本的TypeScriptangularJS.

一个工作的plunker

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

<代码>{"a": "客户 AAA","b": "客户 BBB","c": "客户DDD","d": "客户DDD",默认":未找到"}

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

var app = angular.module('MainApp', ['客户搜索']);angular.module('客户搜索',[])

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

<html ng-app="MainApp" ng-strict-di><头><title>我的应用</title><script data-require="angular.js@*"src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.0-rc.1/angular.js"></脚本><script src="MainApp.js"></script><script src="CustomerSearch.dirc.js"></script><身体><客户搜索></客户搜索>//我们的指令</html>

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

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

///模块客户搜索{var app = angular.module('CustomerSearch');导出类 CustomerSearchDirective 实现 ng.IDirective{公共限制:字符串=E";公共替换:boolean = true;公共模板:string = "

"+"<输入 ng-model=\"SearchedValue\"/>"+"<button ng-click=\"Ctrl.Search()\" >Search</button>"+"<p> 用于搜索值 <b>{{SearchedValue}}</b> " +我们发现:<i>{{FoundResult}}</i></p>"+"</div>";公共控制器:字符串 = 'CustomerSearchCtrl';公共控制器为:字符串 = 'Ctrl';公共范围 = {};}app.directive("customerSearch", [() => new CustomerSearch.CustomerSearchDirective()]);

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

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

 导出接口 ICustomerSearchScope 扩展了 ng.IScope{SearchedValue:字符串;发现结果:字符串;Ctrl:客户搜索Ctrl;}

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

 导出类 CustomerSearchCtrl{静态 $inject = ["$scope", "$http"];构造函数(受保护的 $scope:CustomerSearch.ICustomerSearchScope,受保护的 $http: ng.IHttpService){//去做}公共搜索():无效{这个.$http.get("data.json").then((响应:ng.IHttpPromiseCallbackArg) =>{var data = response.data;this.$scope.FoundResult = 数据[this.$scope.SearchedValue]||数据[默认"];});}}app.controller('CustomerSearchCtrl', CustomerSearch.CustomerSearchCtrl);}

此处操作

中观察所有内容

How to define my controller using TypeScript. As right now it's in angular js but i want to change this for type script.So that the data can be retrieved quickly.

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

解决方案

I decided to add another answer, with working example. It is very simplified version, but should show all the basic how to us TypeScript and angularJS.

There is a working plunker

This would be our data.json playing role of a server.

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

This would be our starting module MainApp.js:

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

angular.module('CustomerSearch',[])

So later we can use module CustomerSearch. This would be our 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>

Now, we would see the declaration of 1) directive, 2) scope, 3) controller. This all could be in one file (check it here). Let's observe all three parts of that file CustomerSearch.dirc.js (it is CustomerSearch.dirc.ts .. but for plunker I complied that)

1) get reference to module 'CustomerSearch' declared above and declare 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()]);

The directive was declared in TypeScript and immediately injected into the our module

Now, we declare a scope to be used as a strongly typed object in Controller:

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

And now we can declare simple controller

    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);
}

Observe that all in action here

这篇关于如何使用 TypeScript 定义我的控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆