angularjs-ng中的自定义指令不工作
我在应用程序中使用bs3模式时尝试过这个代码段,效果很好。 但是,我想将modal和其他一些html标记的代码包装到一个模板中,以便重用angularjs-ng中的自定义指令不工作,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,我在应用程序中使用bs3模式时尝试过这个代码段,效果很好。 但是,我想将modal和其他一些html标记的代码包装到一个模板中,以便重用 <div ng-controller="MainCtrl" class="container"> <h1>Modal example</h1> <button ng-click="toggleModal()" class="btn btn-default">Open modal</button&g
<div ng-controller="MainCtrl" class="container">
<h1>Modal example</h1>
<button ng-click="toggleModal()" class="btn btn-default">Open modal</button>
<div ng-include src="'modal.html'"></div>
<script type="text/ng-template" id="modal.html">
<modal title="Login form" visible="showModal">
<form role="form">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</modal>
</script>
</div>
模态示例
开放模态
电子邮件地址
密码
提交
这是我的名片
然后问题来了。切换按钮只在第一次起作用。
我知道ng include指令将创建一个子作用域,使父作用域中的变量无法访问,但我不知道如何解决这个棘手的问题。有人能帮忙吗
谢谢。我对您的代码做了一些修改,使布尔值驻留在一个对象中,现在您只需观察它: 控制器更改:
mymodal.controller('MainCtrl', function ($scope) {
$scope.modalObj = { showModal : false };
$scope.toggleModal = function(){
$scope.modalObj.showModal = !$scope.modalObj.showModal;
};
});
指令(主要)变更:
当然,这些行现在将引用scope.modalObj.showmodel
,而不是使用parent/attr关键字,通常您应该尽量避免使用这些关键字
如果您删除
scope=true
这意味着如果没有特定的原因需要一个隔离作用域。您的问题将得到解决。如果您想要隔离作用域,那么您可以将该切换变量作为对象属性来更新父作用域。很棒的工作@Omri还有一件事要做,如果您想查看更改,请使用$observe关于属性值。太好了!如果模板中有两个或多个模态会怎么样?@user3505525可能会为每个模态保留不同的对象?@OmriAharon你能看一下吗?如何使代码优雅@user3505525只需添加另一个模型,并使用隔离范围:
scope.$watch(function () { return scope.modalObj.showModal; }, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});