Can指令引用服务信息



我有以下服务:

 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语法的参数时)

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

相关内容

最新更新