Angularjs 角度1.6:can';无法将文本作为组件传递给模态
我有一个工厂:Angularjs 角度1.6:can';无法将文本作为组件传递给模态,angularjs,factory,angular-bootstrap,Angularjs,Factory,Angular Bootstrap,我有一个工厂: ngapp.factory('ErrorService',["$uibModal", function ErrorService($uibModal) { return { showError: function(errorText) { var modalInstance = $uibModal.open({ animation: true, component: 'errorDialog',
ngapp.factory('ErrorService',["$uibModal", function ErrorService($uibModal) {
return {
showError: function(errorText) {
var modalInstance = $uibModal.open({
animation: true,
component: 'errorDialog',
resolve: {
errorText: function () {
return errorText;
}
}
});
}
}
}]);
使用角度引导模式组件的对话框:
angular.module('myapp').component('errorDialog', {
templateUrl: 'errorDialog.html',
controller: function ($scope) {
$scope.title = "Something went wrong!";
$scope.error = $scope.errorText || "Generic error";
$scope.cancel = function () {
this.dismiss({$value: 'cancel'});
};
}
});
…作为模板:
<script type="text/ng-template" id="errorDialog.html">
<div class="modal-header">
<h3>{{$title}}</h3>
</div>
<div class="modal-body" id="dialogBody">
<div class="errorText">{{error}}
<button class="btn btn-primary yes" type="submit" ng-click="cancel()">Ok</button>
</div>
</div>
</script>
您应该向模式组件添加绑定,并使用
this.$onInit
再次将其绑定到$scope
,以确保绑定在解析
完成后发生。。决心
angular.module('myapp').component('errorDialog', {
bindings: {
resolve: '<',
close: '&',
dismiss: '&'
},
templateUrl: 'errorDialog.html',
controller: function ($scope) {
this.$onInit = function() {
$scope.error = this.resolve.errorText;
}
}
});
然后,在模板中,您可以使用:
<span>{{$something.error}}</span>
{{$something.error}
这完全消除了对$scope
的需要,并使调试变得更加容易,因为所有内容都包含在它自己的作用域中(在本例中,是您的模式)。您已绑定到errorText
到$scope
,但它在组件中仍然不可用。这可能非常令人困惑
在你结束所谓的工作之前,尽可能少地使用
$scope
是非常值得的。为你添加了一个小建议确实我混淆了不同示例中的代码,但我最终决定使用你建议的-但我不明白为什么!所以谢谢,非常有用的推荐。
controllerAs: '$something',
controller: function() {
// Bind it to this
var $something = this;
// Use $something instead of $scope from now on
$something.text = 'Hello';
// Or with resolve
$something.$onInit = function() {
$something.error = $something.resolve.errorText;
}
}
<span>{{$something.error}}</span>