栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

我决定添加另一个答案,以描述更多详细信息,如何在其中创建和使用控制器

Typescript
以及如何将其注入
angularJS

这是这个答案的扩展

如何使用Typescript定义控制器?我们也有一个工作的朋克

所以有这个指令:

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

我们可以看到,我们宣布这个指令可作为 ê 字元素。我们还内联了一个 模板 。此模板已准备好绑定

SearchedValue

并在我们的控制器上调用Action
Ctrl.Search()
。我们说的是控制器的名称:“CustomerSearchCtrl”,并要求运行时使其以“ Ctrl”形式提供 (conrollerAs :)

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

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

我们可以使用

$scope
as
ng.IScope
,但是要对其进行更多类型的访问,我们可以创建自己的 接口

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

这样,我们知道,我们有了string

SearchedValue
以及另一个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"]; });    }}

加上其注册到模块

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

这个控制器有什么有趣的地方?它有一个公共actonSearch,可以通过

this.
例如访问其所有膜
this.$http
。因为我们在VS中指示了智能感知,即angular.d.ts类型/接口

protected $http: ng.IHttpService

将被使用,我们以后可以轻松地访问其方法。类似的是返回值的类型

.then()

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

其中确实包含数据:任何类型的{} …

希望对您有所帮助,请注意此处所有操作



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430640.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号