angular.js嵌套指令范围范围属性

时间:2014-05-11 23:01:32

标签: javascript angularjs angularjs-directive

我想要一个“地图”标签,女巫应该包含“标记”标签。

我的问题是我想使用“map”父作用域中的变量设置“marker”属性。

如果我这样做:

    <map center="{{userPosition}}">
        <marker lat="13.555232324" lng="43.555232324" text="Text1" on-click="callback('id_0')" ></marker>
    </map>      

我的代码有效,但我想做的事情如下:

    <map center="{{userPosition}}">
        <marker lat="{{nearRooms['id_0'].lat}}" lng="{{nearRooms['id_0'].lng}}" text="Text1" on-click="callback('id_0')" ></marker>
    </map>      

现在我可以将“lat”作为字符串阅读。

我的地图指令:

ngBMap.directive('map', [ function ($compile){
return {
  restrict: 'E',
  controller: ['$scope', function($scope) {
    this.markers = [];
    $scope.markers = [];
    this.mapHtmlEl = null   
    this.map = null;

    this.exeFunc = function(func, context, args){
        $scope.$parent[func].apply(context, args)
    }
    this.initializeMarkers = function(){
        for (var i=0; i<this.markers.length; i++) {
            var marker = this.markers[i];
            this.map.entities.push(marker);         
        }
    }
    this.initializeMap = function(scope, elem, attrs){
            var map_canvas =  document.createElement('div')
            var _thisCtrl = this;
            ....
        this.mapHtmlEl = map_canvas;    
    }
    this.setCenter = function(position){
        var position = eval(position)
        var _position = new Microsoft.Maps.Location(position[0], position[1])
        if(this.map)
            this.map.setView({center : _position});
    } 
  }],
  scope: {
    'center': '@', 
  },
  link: function(scope, element, attrs, ctrl) {
     scope.$watch('center', function(center) {
        console.log('center: '+center)
        if(center){
            ctrl.setCenter(center)  
        }
      }, false);
    ctrl.initializeMap(scope, element, attrs)
    element.html(ctrl.mapHtmlEl)
  }
}   

}]);

我的标记指示:

ngBMap.directive('marker', [ function ($compile){
return {
  restrict: 'E',
  require: '^map',
  link: function(scope, element, attrs, mapController) {
      console.log('marker init')
        var getMarker = function() {
            var lat = attrs.lat
            .....
            var marker =  _marker;  
            return marker;
        }//end getMarker
        var marker = getMarker();
        mapController.markers.push(marker);
  }
}}]);   

1 个答案:

答案 0 :(得分:1)

假设您使用的是支持controllerAs的Angular版本,您可以执行以下操作:

ngBMap.directive('marker', [ function ($compile){
  return {
    restrict: 'E',
    require: '^map',
    controllerAs: 'marker',
    link: function(scope, element, attrs, mapController) {
      var lat = attrs.lat
<map center="{{userPosition}}">
    <marker lat="{{marker.nearRooms['id_0'].lat}}" lng="{{marker.nearRooms['id_0'].lng}}" text="Text1" on-click="marker.callback('id_0')" ></marker>
</map>      

要使它在Angular 1.0.x中工作,您需要使用scope:true来创建一个继承父指令的子作用域,这样它们就不会相互冲突。