我的 AngularJS Web 应用程序需要(正如您可能猜到的那样)有时显示模式弹出窗口。在学习 AngularJS 之前,我曾经使用命名空间来集中我的代码,并且通常将所有 UI 内容放在适当的命名空间中,例如:MyProj.UI.Dialogs.Modal.show()(只是一个示例) .
现在我尝试在 AngularJS 中应用相同的逻辑。因此,我创建了一个指令:
app.directive('modal', function ($compile) {
return {
restrict: 'E',
replace: true,
templateUrl: '/partials/site/modal.html'
}
});
使用以下模板:
<div>
<h2>{{title}}</h2>
<p>{{text}}</p>
</div>
这样我就可以在我的 html 中使用 modal 标签。
现在,为了控制模态行为,我想使用服务,例如:
angular.module('ui', [])
.factory('ui', function ($rootScope) {
var service = {
showConfirm: function (title, text, callback) {
$rootScope.showModal = true;
}
};
return service;
}
);
我会从任何 Controller 使用它:
app.controller('MyCntl', function (ui) {
$scope.delete = function (referer) {
ui.showConfirm("Confirm", "Please confirm action", function () {});
}
});
但我的问题是:如何将值从 Controller 传递到服务、指令?
最佳答案
这是一个骗子:http://plnkr.co/edit/JLDDsTzSAHaitsZ4dxtL?p=preview
将服务绑定(bind)到指令的范围:
app.directive('modal', function (ui) {
return {
restrict: 'E',
replace: true,
scope:{},
templateUrl: 'modal.html',
link: function(scope){
scope.ui = ui;
}
}
});
服务:
angular.module('ui', [])
.factory('ui', function ($rootScope) {
var _callback = null;
var service = {
confirm: function(confirmed){
if(confirmed) _callback();
service.show = false;
_callback = null;
},
showConfirm: function (title, text, callback) {
service.show = true;
service.title = title;
service.text = text;
_callback = callback;
}
};
return service;
}
);
模板:
<div ng-if="ui.show" class="modal">
<h2>{{ui.title}}</h2>
<p>{{ui.text}}</p>
<button ng-click="ui.confirm(true)">ok</button>
<button ng-click="ui.confirm(false)">cancel</button>
</div>
关于javascript - Angularjs 中从 Controller 到服务再到指令的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22090468/