指令可以引用服务信息吗?

Can directives reference service information?

我有以下服务:

 myapp.service('myService', function () {

      var familyList = this;
      familyList.people = [
        { name: 'Jax', dob: '01/01/1974', cell: '3035551212', carrier: 'ATT', email: 'jax@soa.com', active: true },
        { name: 'Tara', dob: '03/01/1974', cell: '3035551313', carrier: 'SPRINT', email: 'tara@soa.com', active: false }];

 });

我有以下指令:

  myapp.directive('applyplugin', function () {
      return {
          link: function ($scope, myService) {
              $scope.myService = myService;
              alert(myService.people.length);
              $("select[id^='ms']").each(function () {
                  $(option).remove();
              });
          }
      }
  });

我可以从指令中引用 familyList 数组吗?

当然可以,但是服务(依赖项)注入不会发生在 link 函数中,而是发生在定义指令的函数中。

代码变为:

myapp.directive('applyplugin', function (myService) {
    return {
        link: function ($scope) {
            $scope.myService = myService;
            alert(myService.people.length);
            $("select[id^='ms']").each(function () {
                $(option).remove();
            });
        }
    }
});

你不能在 link 函数中注入任何东西,它的签名是固定的并且是 link(scope, element, attributes, ...requiredDirectives) {... } (大多数时候你不会使用最后一个参数,它是当你的指令需要时使用另一个使用 ^someDir 语法)

注意:您可能希望在 link 函数中使用此 element 参数来仅影响指令中的元素:element.find("select[id^='ms']").each( ... )