Ng-click不以angularjs中触发
Ng-click not firing in angularjs?
在这里,我创建了用于按钮单击的示例角度程序。 但它没有发射我可以知道我哪里做错了吗?任何人都可以帮我解决这个问题..谢谢
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $sce) {
$scope.buttonHtml = $sce.trustAsHtml("<button ng-click='showMessage('"foo'")'>click me</button>");
$scope.showMessage = function(message) {
alert(message);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-bind-html="buttonHtml"></div>
</div>
问题是,即使 html 呈现得很好,Angular 实际上也没有将ng-click
绑定到scope
,要做到这一点,你必须先$compile
它。
var compiledHtml = $compile("<button ng-click='showMessage('"foo'")'>click me</button>")($scope);
您需要编译并将元素与正确的范围链接,并替换"旧元素"。这应该通过指令来完成:
.HTML:
<div ng-app="myApp" ng-controller="MyCtrl">
<div replace-with-compiled-html="buttonHtml"></div>
</div>
.JS:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.buttonHtml = "<button ng-click='showMessage('"foo'")'>click me</button>";
$scope.showMessage = function(message) {
alert(message);
}
});
myApp.directive('replaceWithCompiledHtml', function($compile) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function preLink(scope, elem, iAttrs, controller) {
// use the inherited scope -> get the wanted property via the attributes
var scopePropName = iAttrs['replaceWithCompiledHtml'];
// compile the html
var linkingFunc = $compile(scope[scopePropName]);
// link it with the correct inherited scope
linkingFunc(scope, function(newElem) {
// replace the new compiled element with the previous one
elem.replaceWith(newElem);
});
}
};
}
}
});
吉斯菲德尔。
相关文章:
- JQuery.animate();不以固定高度工作
- Grunt concat js angularjs 不起作用
- Angularjs选择以选择数据传递
- Reveal Modal中带有Foundation-Controller的AngularJS不起作用
- angularjs不会污染全球
- Javascript regex仅用于integer,不以0开头,但允许0
- 服务承诺不以业力解决
- AngularJS不会从对象中删除表单
- AngularJS不覆盖内置验证器
- 为什么 AngularJS 不允许异或操作
- 如何在angularjs中以正确的方式在指令中使用ng repeat
- AngularJS和Spring后端-在AngularJS中以user.password的形式从数据库中获取密码
- 为什么不以浏览器特定的字节码发送JavaScript文件呢
- angularjs不起作用的Json响应
- 检查单击的链接's href不以哈希标记开头
- 生成动态表单输入字段,并在angularJS中以数组形式收集字段数据
- 强制用户在angularjs中以0开头
- angularjs不显示国际重音符号和重音符号
- 如何让Require.js获取一个不以“.js”结尾的脚本
- Ng-click不以angularjs中触发