2016-02-27 72 views
1

这里我试图在rightClick上显示数据。我为此创建了一个指令。但数据未正确绑定,它显示为{{data}}。怎样才能克服这个Angular js指令不能编译数据范围

jsFiddle

(function() { 
    var app = angular.module('right', []); 
    app.controller('rightController', function($scope) { 
$scope.template = "<div id='ibacontextmenu' ng-click='click()' temp ngTransclude></div>"; 
$scope.name = 'ajith'; 
$scope.desc = 'Hello'; 
$scope.click = function() { 
    alert('clicked'); 
} 
    }); 
     app.directive('ibaRightMouseDown', function($compile) { 

ibaRightMouseDown = {}; 
ibaRightMouseDown.restrict= 'AE'; 

ibaRightMouseDown.ngModel={}; 
ibaRightMouseDown.link= function(scope, elem, attr) { 
//scope.desc=ngModel; 
    elem.on('contextmenu', function(e) { 
    e.preventDefault(); 
    //scope.desc=scope.ibaRightMouseDown; 

    //scope.desc=scope.ngModel; 
    debugger; 
    scope.$apply(); 
    elem.append($compile("<div id='ibacontextmenu' ng-click='click()' temp></div>")(scope)); 
    $("#ibacontextmenu").css("left", e.clientX); 
    $("#ibacontextmenu").css("top", e.clientY); 
    }); 
    elem.on("mouseleave", function(e) { 

    $("#ibacontextmenu").remove(); 

    debugger; 
    }); 
}; 
return ibaRightMouseDown; 
    }); 
    app.directive('temp',function(){ 
    return{ 
restrict:'A', 
    transclue:true, 
    template:'<div >{{desc}}</div>' 
    }; 
    }); 
})(); 

回答

1

我做了一些更改您的提琴:

  • 删除ngTransclude它似乎并没有无论如何做任何事情。顺便说一句,它应该是ng-transclude当作为一个属性使用。

  • contextmenu事件中添加行$("#ibacontextmenu").remove();作为删除现有上下文菜单的第一条语句。

  • 而不是编译该硬编码的字符串,我通过scope.template$compile服务。

  • 在追加编译的DOM元素之后做了$scope.$apply

JSFiddle available here

+0

谢谢SzabolcsDézsi。非常感谢。 – Ajith