在 AngularJS 控件中调用 jQuery 函数

Call jQuery function inside AngularJS control

对于我的 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);
    }
}

然而只是returns null,什么都没有。

我添加了 jQuery 因为我可以在有效页面上的控制器外部调用 $("#replyContents").wysibb(wbbOpt);

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

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

如果您真的必须使用 jQuery 插件,那么您可以使用 Angular UI Utils JQuery Passthrough 之类的东西,或者您可以创建自己的指令。

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

显然,如果你想使用这个编辑器来做一些像上传图像文件的事情,你必须添加不同类型的 listener/handler。

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>