简体   繁体   English

AngularJS-两种方式绑定跨度

[英]AngularJS - Two way binding an span

I have a text object and I want to bind it to an editable span, since AngularJS provides two-way binding to inputs, but not to spans, I thought just catching the key events and updating the model would be easy. 我有一个文本对象,我想将其绑定到一个可编辑的跨度,因为AngularJS提供了对输入的双向绑定,但不对跨度进行绑定,所以我认为仅捕获关键事件并更新模型将很容易。 Here is my model: 这是我的模型:

angular.module("myApp", [])
    .controller("TextController", function ($scope, $http, $location, $interval) {
        $scope.myText = "my text";
        $scope.updateModel = function () {
            $scope.myText = $("#myspan").html();
        };
        ...
    });

Here is my span: 这是我的跨度:

<span id="myspan" contenteditable="true" ng-keyup="updateModel()" ng-bind="myText"></span>

I'm catching the keyup events and updating the model, however all sorts of weird things happens with the cursor (will jump to the beginning). 我正在捕获keyup事件并更新模型,但是游标会发生各种奇怪的事情(会跳到开头)。 Is there an elegant way to do this? 有没有一种优雅的方法可以做到这一点? Should I just use input or textarea? 我应该只使用输入还是文本区域? I know using span is unorthodox, but seems to work fine in google docs. 我知道使用span是非正统的,但在Google文档中似乎可以正常工作。

Please find below snippet for your answer: 请在下面的代码段中找到您的答案:

In here, you're including jQuery and I would recommend to use angular functionality itself like below . 在这里,您包括jQuery,我建议像下面这样使用角度功能本身。

Mostly we use input tag with ng-model for two way data binding in AngularJS. 通常,我们在AngularJS中使用带有ng-model的输入标签进行双向数据绑定。

 angular.module("myApp", []) .controller("TextController", function($scope, $http, $location, $interval) { $scope.myText = "my text"; $scope.updateModel = function() { $scope.myText = 'abc'; }; $scope.myValue = 'First value' }); 
 <!DOCTYPE html> <html ng-app="myApp"> <head> <script data-require="angularjs@1.5.7" data-semver="1.5.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body ng-controller="TextController"> <h1>Hello Plunker!</h1> <label>Span Value: </label> <span id="myspan" contenteditable="true" ng-keyup="updateModel()" ng-bind="myText"></span><br><br><br> <input type="text" name="myValue" ng-model="myValue" ><br><br> {{myValue}} </body> </html> 

I hope it helps you. 希望对您有帮助。

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM