javascript - 在 AngularJS 控件中调用 jQuery 函数

标签 javascript jquery angularjs wysiwyg

对于我的 AngularJS 应用程序,我需要使用 jQuery 插件 http://www.wysibb.com .

我正在尝试使用 $("#replyContents").bbcode(); 的这个函数应该从 replyContents 中获取内容并给我 BBCode 值。

我想做的是在我的 controller 中,我将范围设置为:

function controlForum($scope) {
    $scope.contents = $("#replyContents").bbcode();

    $scope.btnReply = function() {
        console.log($scope.contents);
    }
}

然而,这只是返回 null,什么都没有。

我包含了 jQuery,因为我可以在有效的页面上的 Controller 外部调用 $("#replyContents").wysibb(wbbOpt);

如何让 bbcode 函数在我的 Angular 函数中运行?

最佳答案

更好的方法是使用编写为原生 AngularJS 指令的文本编辑器。 textAngular挺好的。

如果你真的必须使用 jQuery 插件,那么你可以使用像 Angular UI Utils JQuery Passthrough 这样的插件。或者您可以创建自己的指令。

这是一个使用您自己的指令的示例。要将编辑器的内容与应用于文本区域的 ng-model 同步,您可以要求 ngModel,然后使用 ngModel API 的 $setViewValue 根据某些事件更新模型。在此示例中,我会在“编辑器”div 中触发 keyup 事件以及单击工具栏上的其中一个按钮时进行更新。

显然,如果您想使用此编辑器执行上传图像文件之类的操作,则必须添加不同类型的监听器/处理程序。

angular.module('jqueryplugin.demo', ['wysibb']);

angular.module('jqueryplugin.demo')
.controller('MainCtrl', ['$scope', function($scope){
  $scope.logIt = function(val) {
    console.log(val);
  };
}]);

angular.module('wysibb', [])
.directive('wysibb', function(){
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      var textarea, editor, buttons;
      var options = {
        buttons: 'bold,italic,underline'
      };
      textarea = element.wysibb(options);
      editor = element.next();
      buttons = element.parents('.wysibb').find('.wysibb-toolbar');
      editor.on('keyup', function(){
        scope.$apply(function(){
          ngModel.$setViewValue(editor.html());
        });
      });
      buttons.on('click', function(){
        scope.$apply(function(){
          ngModel.$setViewValue(editor.html());
        });
      });
    }
  };
});
@import url(//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css);
@import url(http://cdn.wysibb.com/css/default/wbbtheme.css);

textarea {
  min-height: 130px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://code.angularjs.org/1.3.16/angular.js"></script>
<script src="http://cdn.wysibb.com/js/jquery.wysibb.min.js"></script>
<div ng-app="jqueryplugin.demo">
  <div ng-controller="MainCtrl">
    <textarea ng-model="text" wysibb></textarea>
    <pre>Output: <code>{{text}}</code></pre>
  </div>
</div>

关于javascript - 在 AngularJS 控件中调用 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31098801/

相关文章:

javascript - 无法识别 JS 服务器,继续构建

javascript - 如何从 12 位数字的开头获取所有文本并使用正则表达式对它们进行分组

java - 如何检查客户端网络/防火墙的端口是否打开?

jquery - 如何使用 select 将两行合二为一?

jquery - 动态改变 jQueryUI 对话框按钮

javascript - 拦截 Angular $http 中的服务器错误并拒绝 Promise

javascript - 处理多个滑动事件 HTML & Javascript/jQuery

jquery.parents()

基于表达式作为关键的 Javascript/AngularJS 对象选择

javascript - UI路由器: deal with nested controllers