angularjs – 将对象作为属性传递给已编译的指令

前端之家收集整理的这篇文章主要介绍了angularjs – 将对象作为属性传递给已编译的指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在页面上有一个角度元素,需要与其他非角度页面元素进行通信.

我正在创建指令元素,并将其附加到其目标div.我试图传递该创建的指令一个对象(ajax对象),它只包含属性.

问题是我无法弄清楚如何将这个ajax对象传递给指令,因为$compile需要一个范围.当http结束,并且因为我必须在指令中使用=时,指令被覆盖.

请看我的插件https://plnkr.co/edit/brTWgUWTotI44tECZXlQ(抱歉图像).点击< button>触发指令.

(function() {
'use strict';
var CHANNEL = 'podOverlay';
angular.module('CavernUI',[])
  .controller('CavernCtrl',function($scope,getItemService) {

    $scope.model = {};
    var _pods = $scope.model.pods = {};

    function getData(selector) {
      $(selector).each(function(i,pod) {
        _pods[+pod.dataset.item] = {
          $: $(pod)
        };
      });

      Object.keys($scope.model.pods).map(function(key) {
        getItemService.getItem(key).success(function(response) {
          _pods[key] = angular.extend(_pods[key],response);
          $scope.$broadcast(CHANNEL,_pods[key],$scope);
        });
      })
    }

    $scope.runPodCheck = function(selector) {
      getData(selector);
    }
  })
  .directive('podchecker',function($compile) {

     var createOverlay = function(e,data,scope){
         scope.data = data;
         // can i just pass data rather than scope.data?
         // If I pass the scope,then when another $broadcast happens
         // the scope updates,wiping out the last scope change.
         // Scope here really needs to be a static object that's
         // created purely for the hand off. But I don't know if 
         // that can be done.
         angular.element(data.$[0]).empty().append($compile('<overlay data="data"></overlay>')(scope));
     }

    return {
      restrict: 'E',scope: {
        check: '&',},templateUrl: 'tpl.html',link: function(scope,elm,attr){
         scope.$on(CHANNEL,createOverlay);
      }
    };
  })
  .directive('overlay',function() {
    return {
      restrict: 'E',scope: {
        o: '=data' // here is the problem. 
      },template: '<div class="overlay"><a href="{{o.url}}"><img ng-src="{{o.images.IT[0]}}"/></a></div>',attr) {

      }
    }
  })
  .service('getItemService',['$http',function($http) {
    this.getItem = function(itemId) {
      return $http({
        method: 'GET',url: 'https://www.aussiebum.com/ajaxproc/item',params: {
          id: itemId,ajxop: 1
        },});
    };
  }]);
}());

编辑:
预期产量:

我不确定这是最好的方法,但一种方法可能是为每个叠加层手动创建一个新的范围.

所以改变了这个:

var createOverlay = function(e,scope){
           scope.data = data;
           angular.element(data.$[0]).empty().append($compile('<overlay data="data"></overlay>')(scope));
       }

对此:

var createOverlay = function(e,scope){
           var overlayScope = scope.$new(false); // use true here for isolate scope,false to inherit from parent
           overlayScope.data = data;
           angular.element(data.$[0]).empty().append($compile('<overlay data="data"></overlay>')(overlayScope));
       }

更新了Plnkr:https://plnkr.co/edit/wBQ1cqVKfSqwqf04SnPP

有关更多信息$new()

干杯!

猜你在找的Angularjs相关文章