Проблема с несколькими дочерними элементами HTML с использованием директив в AngularJS
Я использую шаблон для создания всплывающего меню, в котором будут отображаться предупреждения, если есть новый, и он работает до сих пор. Но я хотел добавить ручное предупреждение, поэтому я решил добавить текст ввода, но 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());
}
}
}
});
Я попытался сделать область правдой, но я столкнулся с двумя проблемами:
Я больше не могу перемещать всплывающее окно (да, мое всплывающее меню Draggable)
И также текст ввода не отображает мой текст, который я печатаю.
Вот мой шаблон кеша:
$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>');
Я новичок в AngularJS и Directive, и я не знаю, как это решить, но я думаю, что это проблема с Scopes!!
Спасибо.
ОБНОВЛЕНИЕ:
Если я удалю область: {menu: "= drSrc" } Это работает, и я могу ввести то, что хочу, но проблема в том, что мой элемент больше не перетаскивается.
Я думаю, что это связано с областями. может кто-нибудь помочь?
Ответы
Ответ 1
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
данные, которые использует ваш шаблон.
Эти записи полезны для понимания директив и областей:
Ответ 2
В настоящее время я работаю над проектом, который сильно зависит от модальных диалогов. Каждый со своей целью и динамическим контентом.
Здесь система, с которой я работал:
index.html
<!doctype html>
<html ng-app="myApp" ng-controller="MainCtrl">
<head>
<title>Dialogs</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<button ng-click="openDialog()">Open Dialog</button>
<modal-dialog show="showMe" dialog-controller="WelcomeDialogCtrl" context="welcome"></modal-dialog>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
app.js
var app = angular.module('myApp', []);
// The main controller, which will handle index.html
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.showMe = false;
$scope.openDialog = function(){
$scope.showMe = true; // Show the 'welcome' dialog
};
}]);
// The modal dialog directive
app.directive('modalDialog', [function() {
return {
controller: '@', // Bind a controller
name: 'dialogController', // Bind the controller to this attribute name
restrict: 'E',
scope: {
show: '='
},
link: function(scope, element, attrs) {
// Close this dialog (actually ng-hides it)
scope.closeDialog = function() {
scope.show = false;
};
},
templateUrl: function(element, attrs){
// I prefer to load my dialog templates from a separate folder to keep my project tidy
return 'dialogs/' + attrs.context + '.html';
}
};
}]);
// The 'welcome' dialog has its own controller with its own scope
app.controller('WelcomeDialogCtrl', ['$scope', function($scope){
// This can be called by the template that resides within the directive
$scope.exampleFunction = function(text){
console.log('Example function says: ' + text);
};
}]);
welcome.html
<div class="dialog" ng-show="show">
<div class="dialog-overlay"></div>
<div class="dialog-box">
Welcome, be sure to check out this blazin' dialog.
<button ng-click="exampleFunction('Hi!')">Say Hi!</button>
<button ng-click="closeDialog()">Close</button>
</div>
</div>
app.css
body{
background: #eee;
margin: 80px;
}
/*
* Just some fancy schmuck
*/
button{
border-radius: 5px;
background: #272;
color: #fff;
padding: 5px 12px;
border: 0;
}
/*
* The grey, transparent curtain.
*/
.dialog-overlay {
width: 100%;
height: 100%;
position: absolute;
background: #111;
opacity: 0.2;
top: 0;
left: 0;
z-index: 100;
}
/*
* The dialog itself. Horribly centered.
*/
.dialog-box{
background: #fff;
border-radius: 5px;
padding: 10px 20px;
position: absolute;
width: 600px;
height: 300px;
top: 50%;
left: 50%;
margin-left: -300px;
z-index: 110;
}
Я также сделал Plunker с тем же кодом.