使用AngularJS中的Directives发出多个子HTML元素

Ayy*_*oub 14 javascript html5 angularjs angularjs-directive angular-template

我正在使用一个模板创建一个弹出菜单,如果有一个新的,它将显示警报,并且它一直在工作.但我想添加手动警报,这就是为什么我想添加输入文本但是Oupss,我不能在输入字段上写,我甚至不知道为什么.输入字段有点被禁用!!!

我的指示是这样的:

$scope.tb = { x: 0, y: 0 };

module.directive('myDraggable', function ($document, $interval) {
return {
    restrict: 'EA',
    replace: true,
    //scope : true,
    scope: { menu: '=drSrc'},
    link: function (scope, element, attr) {

        var startX = 0, startY = 0, x = scope.menu.x || 0, y = scope.menu.y || 0, positionX = [], positionY = [], time = [], width, height, moveInterval;

        element.draggable({
            position: 'relative',
            cursor: 'pointer',
            top: y + 'px',
            left: x + 'px'
        });

        element.on('mousedown', function (event) {

            // Prevent default dragging of selected content
            event.preventDefault();
            startX = event.pageX - x;
            startY = event.pageY - y;
            $document.on('mousemove', mousemove);
            $document.on('mouseup', mouseup);
            $interval.cancel(moveInterval);
        });

        function mousemove(event) {
            y = event.pageY - startY;
            x = event.pageX - startX;
            //calculate the borders of the document 
            width = $(document).width() - 350;
            height = $(document).height() - 150;
            positionX.push(x);
            positionY.push(y);
            time.push(Date.now());
        }
    }
}
 });
Run Code Online (Sandbox Code Playgroud)

我试图使范围成立但我面临两个问题:我不能再移动我的弹出窗口了(是的,我的弹出菜单是可拖动的)而且输入文本也没有显示我输入的文本.

这是我的缓存模板:

    $templateCache.put('control.tpl.html', '<div class="container" my-draggable dr-src="tb"><div><div class="col-sm-1 col-md-1 sidebar"><div class="list-group" ><span href="#" class="list-group-item active" >Manage<input type="text" class="pull-right" placeholder="Type..." /></span><div ng-repeat="Alert in Alerts"><a href="#" ng-click="showLocation(Alert.id)" class="list-group-item" >Alert {{Alert.id}}</span><img src="../images/alert_icon_manage.png"  class="pull-right"/> </a></div><span href="#" class="list-group-item active"></span></div></div></div></div>');
Run Code Online (Sandbox Code Playgroud)

我是AngularJS和Directive的新手,我不知道如何解决这个问题,但我认为这是Scopes的一个问题!谢谢.

更新:

如果我删除范围:{menu:"= drSrc"}这项工作,我可以键入我想要的但问题是我的元素不再可拖动.我认为这与范围有关.有人可以帮忙吗?

Kri*_*ján 4

scope: true指示您的指令应继承其父级的作用域,但scope: {menu: '=drSrc'}会创建一个隔离的作用域,从而删除您的模板对Alerts. 当您删除 时scope: {menu: '=drSrc'}menu不再存在,因此scope.menu.x失败并且您的元素不再可拖动。

最简单的修复方法是使用scope: true和引用scope.drSrc.x等而不是scope.menu.x. 通过scope: true,您可以访问父级的范围,包括您的模板正在使用的drSrc数据Alerts

这些文章对于理解指令和范围很有用: