这里是 Angular 菜鸟。我正在尝试创建一个表单作为指令。 ng-submit 调用 Controller 操作,但是,在该方法中,我无权访问 Controller 范围,即。 $范围
。
这是真正让我困惑的部分。在我的笔记本电脑和台式机上,当我第一次进入 submit()
中的 debugger
时,$scope
仍在范围内。以后的每一次,都不是这样。
我让一位同事测试了这段代码,但他们无法重现它。
编辑:如果我当时没有在 $scope.submit
中进入调试器,它就可以正常工作。
course-material-form.js.coffee
angular
.module 'app'
.directive 'courseMaterialForm', () ->
restrict: 'EA'
templateUrl: 'app/shared/coursework/course-material/templates/_form.html'
scope:
book: '='
model: '='
controller: 'CourseMaterialFormCtrl'
类(class) Material 形式-ctrl.js.coffee
angular
.module 'app'
.controller 'CourseMaterialFormCtrl', ($scope) ->
$scope.submit = () ->
return
_form.html.haml
%form.form-compact#course-material-form{ "ng-submit" => "submit()" }
%fieldset.row
.form-group.col-xs-12
%label Title
%input{ type: 'text', "ng-model" => " book.title " }
.form-group.col-md-6.col-xs-12
%label Author
%input{ type: 'text', "ng-model" => " book.author " }
%fieldset.row
.form-group.col-md-6.col-xs-12
%label Publisher
%input{ type: 'text', "ng-model" => " book.publisher " }
.form-group.col-md-6.col-xs-12
%label Publication Year
%input{ type: 'text', "ng-model" => " book.publication_date " }
.form-group.col-md-6.col-xs-12
%label Edition
%input{ type: 'text', "ng-model" => " book.edition " }
.form-group.col-md-6.col-xs-12
%label ISBN
%input{ type: 'text', "ng-model" => " book.isbn " }
%fieldset.row
.form-group.col-xs-12
%label Description
%textarea{ "ng-model" => "book.description" }
%fieldset.row.hidden
.form-group.col-md-6.col-xs-6
%label URL
%input{ type: 'text' }
_modal.html.haml
.modal-dialog.modalbox-dialog.coursework-form-modal
.modal-content
%header.modal-header.modal-header-lg
.modal-heading
%span{ "ng-if" => "!book" } Add
%span{ "ng-if" => "book" } Edit
Course Material
%button.modal-close-btn.modal-close-icon{ "ng-click" => "$dismiss()" }
%i.fa.fa-times-circle
.modal-body
%course-material-form{ model: "model", book: "book" }
.modal-footer
%button.btn.btn-primary.modal-footer-btn{ form: "course-material-form",
type: "submit" }
%span{ "ng-if" => "!book" } Create
%span{ "ng-if" => "book" } Save
%button.btn.btn-outline.modal-footer-btn{ "ng-click" => "$dismiss()",
type: "button" }
Close
最佳答案
Controller
中的submit
函数和指令
中的submit
函数不同。它们属于不同的$scope
。有关它的更多信息,请参阅 Directive's guide 中的“隔离指令的范围”部分。
由于您要隔离指令的范围,因此您应该将提交函数从 Controller “公开”到指令,如下所示:
scope: {
book: '=',
model: '=',
submit: '&' // <- that's what you need
}
然后在您的 _modal.html
上传递一个新属性:
.modal-body
%course-material-form{ model: "model", book: "book", submit: "submit()" }
关于javascript - AngularJS - 在方法内丢失 Controller 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30720722/