Angular指令使用Typescript接收对象作为属性

时间:2016-10-05 19:34:33

标签: angularjs typescript angularjs-directive typescript1.8

我正在使用Angular 1.5.8和Typescript进行开发 我有一个指令,在另一个指令(当然是另一个控制器)的范围内使用。让我们说Directive1,Controller1和Directive2,Controller2。 鉴于Controller1已经拥有用户信息,我想通过Directive2将此用户信息传递给Controller2,以防止再次从后端获取信息。 我不确定这是否可以做到,但如果是这样的话会很好:)

以下是帮助我解释的代码:

Directive1 HTML:

<div>
    ...
    <directive2 user="{{ctrl.loggedUser}}"></directive2>
    ...
</div>

loggedUser通过调用后端在Controller1构造函数中加载。

Directive2和Directive2Ctrl Typescript代码:

class Directive2 implements ng.IDirective {
    controller = "Directive2Ctrl";
    controllerAs = "d2Ctrl";
    bindToController = {
        user: "@"
    };
    restrict = "E";
    templateUrl = "directive2.html";

    static factory(): ng.IDirectiveFactory {
        const directive = () => new Directive2();
        return directive;
    }
}
angular
    .module("app")
    .controller("Directive2Ctrl", Directive2Ctrl)
    .directive("directive2", Directive2.factory());


class Directive2Ctrl implements IDirective2Ctrl {
    public user: User;

    constructor(user: User) {
         // user is undefined
    }

    $onInit(user: User): void {
        // user is undefined
    }
}

我找不到将用户对象传递给Directive2Ctrl的方法(甚至不确定是否可行)。

5 个答案:

答案 0 :(得分:4)

使用&#34;范围&#34;属性而不是&#34; bindToController&#34;财产,并替换你的&#34; @&#34;与&#34; =&#34;。 然后我使用我的特定范围的接口来获得自动完成。

export interface IMyDirectiveScope extends ng.IScope {
    user: any;
}

export class Myirective {
    public restrict: string = 'E';
    public templateUrl = "/mytemplate.html";
    public link: (scope: IMyDirectiveScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModel: ng.INgModelController) => void;
    public scope = {
        user: "="
    };

    constructor() {
        var context = this;
        context.link = (scope: IMyDirectiveScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModel: ng.INgModelController) => {
           //INSERT YOUR CODE
           //console.log(scope.user);
        };
    }

    public static Factory() {
        var directive = () => {
            return new MyDirective();
        };

        return directive;
    }
}

在你的html中,删除花括号。

<div>
    ...
    <directive2 user="ctrl.loggedUser"></directive2>
    ...
</div>

答案 1 :(得分:2)

如果您想在应用程序的不同位置之间共享数据,只需将其放入服务中,并在需要数据的地方使用DI。

即,获取数据,将其存储在服务中并使用DI使数据在不同位置可用。无需通过多个层的绑定传递数据,更容易使用服务。

var mod = angular.module('testApp', ['ngRoute']);

mod.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/intern', {
        template: '<div class="outer" ng-controller="InternController">{{User.firstName}} <div class="nested" ng-controller="NestedController">{{NestedUser.lastName}}<test-dir></test-dir></div></div>',
        resolve: {
          userResolve: function($q, $timeout, User) {
            var deferred = $q.defer();
          
            // mock server call, which returns server data
            $timeout(function() {
              var mockUserResp = {
                firstName: 'John',
                lastName: 'Rambo'
              };
              User.setUser(mockUserResp);
            
              deferred.resolve();
            }, 1000);
          
            return deferred.promise;
          }
        }
      }).
      otherwise({
        redirectTo: '/intern'
      });
  }]);

mod.factory('User', function() {
  var _user = null;
  return {
    setUser: function(user) {
      _user = user;
    },
    getUser: function() {
      return _user;
    }
  }  
});

mod.controller('InternController', function($scope, User) {
  $scope.User = User.getUser();
});

mod.controller('NestedController', function($scope, User) {
  $scope.NestedUser = User.getUser();
});

mod.directive('testDir', function(User) {
  return {
    restrict: 'EA',
    scope: {},
    template: '<div class="dir">{{firstName}} is a cool guy.</div>',
    link: function(scope) {
      scope.firstName = User.getUser().firstName;
    }
  };
});
.outer {
  border: 1px solid green;
}

.nested {
  border: 1px solid blue;
}

.dir {
  border: 1px solid orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.12/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.12/angular-route.min.js"></script>


<div ng-app="testApp">
  <div ng-view></div>
</div>

答案 2 :(得分:2)

应该是这样的。但如果它仍然不适合你,你可以创建一个简单的plunker,我会在那里修复它。干杯!

<div>
    ...
    <directive2 user="ctrl.loggedUser"></directive2>
    ...
</div>

`

class Directive2 implements ng.IDirective {
    controller = "Directive2Ctrl";
    controllerAs = "d2Ctrl";
    scope = {},
    bindToController = {
        user: "="
    };
    restrict = "E";
    templateUrl = "directive2.html";

    static factory(): ng.IDirectiveFactory {
        return () => new Directive2();
    }
}
angular
    .module("app")
    .controller("Directive2Ctrl", Directive2Ctrl)
    .directive("directive2", Directive2.factory());


class Directive2Ctrl implements IDirective2Ctrl {
    public user: User;

    $onInit(user: User): void {
        // user should be available
        console.log(this.user);
    }
}

答案 3 :(得分:0)

抱歉,我想知道您是否还需要设置scope = {}

答案 4 :(得分:0)

要做我刚才提出的问题,需要正确使用范围。

这是另一个很好地解释的问题,正确使用范围:

How can I define my controller using TypeScript?