在角度指令中共享变量

时间:2015-04-28 17:09:30

标签: angularjs

我的指令很少,比如

app.directive('navContent', function() {
return {
    restrict: 'E',
    scope: {
        content: "="
    },
    templateUrl: '../../' + template + '/regions/nav.html',
}
});


app.directive('headerContent', function() {
return {
    restrict: 'E',
    scope: {
        content: "="
    },
    templateUrl: '../../' + template + '/regions/header.html',
}
});

都需要templateURL中的模板var。

我尝试过没有成功的功能

var siteID = angular.element('head').data('site-id');
$http.get('/api/sites/' + siteID)
    .success(function(site) {
        var template = site.template;   
       })
    .error(function(data) {
        console.log('Error: ' + data);
    });
};

siteID在DOM中:

<head data-site-id="123456">

和site.template应从站点模型返回模板

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:1)

您最好选择在$rootScope中设置此变量。然后,这将适用于您的所有指令。

编辑:改为使用:document.head.dataset.siteId

var siteID = angular.element('head').data('site-id');
$http.get('/api/sites/' + siteID).success(function(site) {
  $rootScope.template = site.template;   
  }).error(function(data) {
    console.log('Error: ' + data);
  });
};

您现在可以动态地将模板编译到指令中。

app.directive('headerContent', function() {
  return {
    restrict: 'E',
    scope: true,
    link: function(scope, element, attrs){
      var linkFn;
      var templateUrl = '../../' + scope.template + '/regions/header.html';

      $http.get(templateUrl).then(function(response) {
        linkFn = $compile(response.data);
        element.html(linkFn(scope));
      });   
    }
  }
});

编辑:正如评论中所提到的,有很多方法可以实现这一点,基本上你想要将data值放入编译函数中。您可以使用我不会在生产中使用的$rootScope或服务。但是,数据不太可能会改变,所以你甚至可能更喜欢使用类似的东西。

 .directive('myDirective', function ($http) {
        return {
            restrict: 'E',
            scope: true,
            link: function(scope, element, attrs){
                var linkFn;
                var templateUrl = '../../' + document.head.dataset.siteId + '/regions/header.html';
                $http.get(templateUrl).then(function(response) {
                    linkFn = $compile(response.data);
                    element.html(linkFn(scope));
                });
            }
        }
    });

答案 1 :(得分:1)

您可以使用Javascript通过document.head.dataset.siteId

从HTML中获取数据属性

工作示例 - &gt; http://jsbin.com/cijukinoca/1/edit?html,js,output收听网络请求。它会显示Request URL: http://null.jsbin.com/123456/regions/header.html

app.directive('headerContent', function() {
  return {
    restrict: 'E',
    scope: {
        content: "="
    },
    templateUrl: '../../' + document.head.dataset.siteId + '/regions/header.html',
  }
});

答案 2 :(得分:0)

使用$rootScope分享数据,如@Edward Knowles的回答,完全合法且效果很好。

但是,通过将数据放在$rootScope上,您将数据放在应用程序中的每个其他$scope上。这可能不太理想(可变冲突,破坏封装,单元测试更脆弱等)。

共享数据的另一种方法是使用Angular服务/工厂。这会将数据放入您可以注入所有控制器/指令的内容中。

app.service('SharedData', function() {
  var service = {
    foo: 'bar',
    baz: 'bip'
  };

  return service;

});


app.directive('myDirective', function(SharedData) {
  // do something w/SharedData
});
相关问题