我想点击一个按钮,用表格替换变量。我该怎么做?
var MainCtrl = angular.module('mainCtrl', []);
MainCtrl.controller('MainCtrl', function ($scope) {
$scope.bar = 'Foo';
$scope.foo = function(){
$scope.bar = '<form class="form-inline" role="form"> <div class="form-group"> <label class="sr-only" for="exampleInputEmail2">Email address</label> <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Enter email"> </div> <div class="form-group"> <label class="sr-only" for="exampleInputPassword2">Password</label> <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password"> </div> <div class="checkbox"> <label> <input type="checkbox"> Remember me </label> </div> <button type="submit" class="btn btn-default">Sign in</button> </form>';
}
});
var fooApp = angular.module(
'fooApp', ['ngSanitize', 'mainCtrl'];
);
<body ng-app='fooApp' ng-controller="MainCtrl">
<div ng-bind-html="bar"></div>
<button class="btn" ng-click="foo()">Change bar to form</button>
</body>
答案 0 :(得分:1)
这不是一种非常有角度的方法。
通常,您的控制器从不包含任何标记,也不应直接与DOM交互。
我建议设置变量以确定是否已单击该按钮,然后使用ngShow和ngHide有条件地显示内容或表单。
以下是一个例子:
HTML:
<body ng-app='fooApp' ng-controller="MainCtrl">
<div ng-hide="showForm">Foo</div>
<form class="form-inline" role="form" ng-show="showForm"> <div class="form-group"> <label class="sr-only" for="exampleInputEmail2">Email address</label> <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Enter email"> </div> <div class="form-group"> <label class="sr-only" for="exampleInputPassword2">Password</label> <input type="password" class="form-control" id="exampleInputPassword2" placeholder="Password"> </div> <div class="checkbox"> <label> <input type="checkbox"> Remember me </label> </div> <button type="submit" class="btn btn-default">Sign in</button></form>
<button class="btn" ng-click="foo()">Change bar to form</button>
</body>
JS:
MainCtrl.controller('MainCtrl', function ($scope) {
$scope.showForm = false;
$scope.foo = function() {
$scope.showForm = true;
}
});
这是Plunker。
如果符合您的需求,请告诉我。有很多选项可以避免在控制器中使用标记。