为什么下面的输入按钮不会调用login()
控制器内的InitCtrl
功能?
<html lang="en" ng-app="mvc-module" class="ng-scope"><head>
<meta charset="utf-8">
<title>Sign in</title>
<script src="/SpringMVC/static/todo.js"></script>
</head>
<body>
<div ng-controller="InitCtrl" ng-bind-html-unsafe="mainPage" class="ng-scope ng-binding">
<!------ this part of code is injected by binding model of Angularjs -->
<div class="container">
<input type="button" ng-click="login()" value="Sign in" class="btn btn-large btn-primary">
</div>
<!--- end of injection --->
</div>
</body></html>
这是todo.js
:
function InitCtrl($scope, $http) {
$scope.login = function () {
console.log("In login!");
$http.post("login", {password: $scope.password, username: $scope.username}).
success(function (data, status, headers, config) {
$scope.mainPage = data;
console.log("successfully logged to login");
}).error(function (data, status, headers, config) {
console.log("error in post");
});
};
$http.get("login").success(function (data, status, headers, config) {
$scope.mainPage = data;
});
}
这不是问题的{fiddler版本http://jsfiddle.net/pooyaho/M8krc/4/
答案 0 :(得分:3)
我们希望使用ng-bind-html-unsafe
插入HTML,因此ng-click
不起作用。为了使其工作,我们需要使用$compile
服务编译此来源。
所以让我们创建“compilator”:
.directive( 'compileData', function ( $compile ) {
return {
scope: true,
link: function ( scope, element, attrs ) {
var elmnt;
attrs.$observe( 'template', function ( myTemplate ) {
if ( angular.isDefined( myTemplate ) ) {
// compile the provided template against the current scope
elmnt = $compile( myTemplate )( scope );
element.html(""); // dummy "clear"
element.append( elmnt );
}
});
}
};
});
之后,让我们创建模拟服务器响应的虚拟factory
:
.factory( 'tempService', function () {
return function () {
// $http.post("login", {password: $scope.password, username: $scope.username}).
// success(function (data, status, headers, config) {
//
// console.log("successfully logged to login");
// return data;
// }).error(function (data, status, headers, config) {
// console.log("error in post");
// return "error";
// });
// obviously would be $http
return '<form class= "form-signin" >' +
'<h2 class="form-signin-heading">Please sign in</h2>' +
'<input type = "text" class= "input-block-level" placeholder = "User name" ng-model = "username" >' +
'<input type="password" class="input-block-level" placeholder="Password" ng-model="password">' +
'<label class="checkbox">' +
'<input type="checkbox" value="remember-me" ng-model="remember"> Remember me' +
'</label>' +
'<input type="button" class="btn btn-large btn-primary" ng-click="login()" value="Sign in">' +
'</form>';
};
});
最后让我们将指令添加到HTML:
<div compile-data template="{{mainPage}}"></div>
当然,我们需要在控制器中注册我们的factory
和directive
:
$scope.mainPage= tempService();
您可以在此处找到工作示例: FIDDLE
答案 1 :(得分:1)
ng-bind-html-unsafe
,如果你使用它会抛出错误。