Ok-ed编辑添加代码。
我无法将javascript函数绑定到角色包含的html页面中的元素。
这有效:
<button id="toggleMessage">Click Me</button>
<script src="/Scripts/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
var globalFunctions = function () {
var init = function () {
toggleMenuLeft();
};
var toggleMenuLeft = function () {
$('#toggleMessage').bind('click', function (e) {
alert("Hello");
});
};
return {
init: init,
};
}();
//Load global functions
$(document).ready(function () {
globalFunctions.init();
});
</script>
一旦我将该按钮移动到包含它就不再有效了。我尝试将.click更改为.on但仍然无效:
#ParentPage.html
<body ng-app="myapp">
<div ng-include="'/IncludePage.html'"></div>
<script src="/Scripts/jquery-2.1.0.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
var globalFunctions = function () {
var init = function () {
toggleMenuLeft();
};
var toggleMenuLeft = function () {
$('#toggleMessage').bind('click', function (e) {
alert("Hello");
});
};
return {
init: init,
};
}();
//Load global functions
$(document).ready(function () {
globalFunctions.init();
});
</script>
</body>
#IncludePage.html
<button id="toggleMessage">Click Me</button>
从topnav调用的真实代码包括在leftnav include中查找#toggle-left。 https://gist.github.com/anonymous/11084106
#RealCode - For Matt
var toggleMenuLeft = function () {
$(document).on('click', '#toggle-left', function (e) {
if (!$('.sidebarRight').hasClass('.sidebar-toggle-right')) {
$('.sidebarRight').removeClass('sidebar-toggle-right');
$('.main-content-wrapper').removeClass('main-content-toggle-right');
}
$('.sidebar').toggleClass('sidebar-toggle');
$('.main-content-wrapper').toggleClass('main-content-toggle-left');
e.stopPropagation();
});
};
答案 0 :(得分:1)
将jQuery与AngularJs混合似乎很简单,但会导致麻烦。理想情况下,您应该将此逻辑放在控制器或指令中。
#IncludePage.html
<div ng-controller="PageCtrl">
<button id="toggleMessage" ng-click="toggle()">Click Me</button>
</div>
app.controller("PageCtrl", [$scope, function($scope){
$scope.toggle = function(){
//do something
};
}]);
#IncludePage.html
<button id="toggleMessage" toggle="">Click Me</button>
app.directive("toggle", function(){
return {
restrict: "A",
link : function(scope, element, atts){
$(element).bind('click', function (e) {
alert("Hello");
});
}
}
});
答案 1 :(得分:0)
啊,我找到了这个答案:jQuery click events not firing within AngularJS templates这与Matt所说的一致。我只需要把它放在文档元素上。
解决方案
var toggleMenuLeft = function () {
$(document).bind('click', '#toggleMessage', function (e) {
alert("Hello");
});
};