如何使用 TypeScript Controller 和 Angular Js 绑定数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30501735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:01:01  来源:igfitidea点击:

How To bind data using TypeScript Controller & Angular Js

javascriptangularjstypescriptangularjs-ng-repeat

提问by Shian JA

I am Playing around with Type Script.I have convert my angular js controller to Type Script But i m facing problem in ng-repeater. (I have attached my controller code below:-

我正在玩 Type Script。我已将我的 angular js 控制器转换为 Type Script 但我在 ng-repeater 中遇到了问题。(我在下面附上了我的控制器代码:-

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

采纳答案by Radim K?hler

I decided to add another answer describing more details how to create and use controller in TypeScriptand inject it into angularJS.

我决定添加另一个答案,描述如何在其中创建和使用控制器TypeScript并将其注入angularJS.

This is extension of this Answer

这是这个答案的扩展

How can I define my controller using TypeScript?Where we also have a working plunker

如何使用 TypeScript 定义我的控制器?我们还有一个工作的plunker

So having this directive:

所以有这个指令:

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 = {};
}

We can see, that we declared this directive to be available as Element. We also in-lined a template. This template is ready to bind SearchedValueand call Action on our controller Ctrl.Search(). We are saying what is the name of controller: 'CustomerSearchCtrl' and asking runtime to make it available as 'Ctrl' (conrollerAs:)

我们可以看到,我们声明该指令可用作E元素。我们还内联了一个模板。此模板已准备好在SearchedValue我们的控制器上绑定和调用 Action Ctrl.Search()。我们说的是控制器的名称是什么:“CustomerSearchCtrl”并要求运行时将其作为“Ctrl”使用(conrollerAs :)

Finally we inject that object into angular module:

最后,我们将该对象注入 angular 模块:

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

We can use $scopeas ng.IScope, but to have more typed access to it, we can create our own interface:

我们可以使用$scopeas ng.IScope,但要对其进行更多类型的访问,我们可以创建自己的界面

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

This way, we know, that we have string SearchedValueand also other string FoundResult. We also informed the application that Ctrl will be injected into that scope, and will be of type CustomerSearchCtrl. And here comes that controller:

这样,我们知道,我们有 stringSearchedValue和其他 string FoundResult。我们还通知应用程序 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"];
            });
    }
}

plus its registration into module

加上它在模块中的注册

app.controller('CustomerSearchCtrl',  CustomerSearch.CustomerSearchCtrl);

What is interesting on this controller? it has one public acton Search, which has access to all its membes via this., e.g. this.$http. Because we instructed intellisense in VS that angular.d.ts type/interface

这个控制器有什么有趣的地方?它有一个公共行动搜索,它可以通过this.例如访问其所有成员this.$http。因为我们在VS中指示了intellisense那个angular.d.ts类型/接口

protected $http: ng.IHttpService

will be used, we can later easily access its methods. Similar is the type of returned value in .then()

将被使用,我们以后可以很容易地访问它的方法。类似的是返回值的类型.then()

.then((response: ng.IHttpPromiseCallbackArg<any>) => {...

which does contain data: {} of any type...

其中包含数据:{} 任何类型...

Hope it helps a bit, observe that all in action here

希望对您有所帮助,请注意这里的所有操作

回答by Radim K?hler

There is one issue with your constructor and $inject- these must fit together

您的构造函数存在一个问题$inject- 这些必须组合在一起

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

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

What happened in fact - all params were moved in the meaning, that $httpwas $scopein fact, etc...

其实发生了什么事-所有PARAMS的含义被感动了,这$http$scope在事实上,等...

Simply, $injectarray MUST fit to constructor parameter list

简单地说,$inject数组必须适合构造函数参数列表

BTW, that's why I had previously here: https://stackoverflow.com/a/30482388/1679310suggested to use types in the declaration:

顺便说一句,这就是我之前在这里的原因:https: //stackoverflow.com/a/30482388/1679310建议在声明中使用类型:

   constructor(protected $scope: ICustomerScope,
        protected $http: ng.IHttpService,
        protected $templateCache: ng.ITemplateCacheService)
    { ... }

回答by Hyman Yum Cha

The library Bindable TSis an alternative way to set up data binding with typescript.

Bindable TS是使用 typescript 设置数据绑定的另一种方法。

回答by Mikalai

From quick review of your code I have found that searchmethod of controller is private. May be changing it to public will solve problem.

通过快速查看您的代码,我发现search控制器的方法是私有的。可能将其更改为 public 将解决问题。