angularJS + jQuery可编辑插件一起工作

时间:2013-10-04 12:33:03

标签: javascript jquery angularjs angularjs-directive

我正在尝试为jeditable插件编写一个指令,所以当它更改值时,它也会更改编辑已编辑元素的模型。

所以我写了类似的东西,JS Fiddle 但我不知道如何获取绑定到列表中对象的对象。

JS:

var app = angular.module("app", []);

app.controller('ctrl', function ($scope) {
    $scope.lst = [{
        id: 1,
        name: "item1"
    }, {
        id: 1,
        name: "item1"
    }, {
        id: 2,
        name: "item2"
    }, {
        id: 3,
        name: "item3"
    }, {
        id: 3,
        name: "item3"
    }];
});

app.directive('uiEditable', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.editable("/echo/json/", {
                onblur: 'submit',
                onsubmit: function (response, settings) {
                    //here i need to update the model
                }
            });
        }
    };
});

3 个答案:

答案 0 :(得分:3)

这使用ngModel更新回模型。 (所以不要忘记元素上的ng-model)

app.directive('uiEditable', function () {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModel) {
            if (!ngModel) return; // do nothing if no ng-model

            element.editable(function (val) {
                var tVal = $.trim(val);
                if (ngModel.$viewValue !== tVal)
                     scope.$apply(function () { return ngModel.$setViewValue(tVal); });
                return tVal;
            });
        }
    };
});

答案 1 :(得分:2)

为什么使用jeditable插件?这个插件似乎只在jQuery中复制了你已经可以单独使用ng-model完成的角度,并且不需要插件。

如果您只想创建可以像jEditable那样进行编辑的文本,而不是简单地使用ng-submit,ng-click,ng-hide和ng-model创建自定义指令。这是一个粗略的例子。

观点:

<form ng-submit="submit()">
  <div ng-hide="showEdit"
       ng-click="showEdit = true">
       {{foo.bar}}
  </div>
  <div>
    <input  type="text"
            ng-show="showEdit"
            ng-model="foo.bar" />
  </div>
  <a href="#" ng-show="showEdit" 
              ng-click="submit();">done</a>
</form>

控制器:

app.controller('myCtrl', function($scope) {

  $scope.foo = {
    bar: 'some text'
  };

  $scope.showEdit = false;

  $scope.submit = function() {
    // hide the edit field
    $scope.showEdit = false;
    // submit form
    console.log('submit form');
  }

});

答案 2 :(得分:-1)

将您的物品放在隔离的范围内:

app.directive('uiEditable', function(){
    return {
        restrict: 'A',
        scope: {
            item: '='
        },
        link: function(scope, element, attrs){
            element.editable("/echo/json/", {
                onblur: 'submit',
                onsubmit: function(response, settings){
                    alert(scope.item);
                }
            });
        }
    };
});

&#39; scope.item&#39;现在将为您提供指令中项目的引用。