从指令引用ng-model parent

时间:2014-02-07 17:46:44

标签: angularjs coffeescript pug

所以我有以下Jade模板:

  div(ng-controller="TodoListController", ng-init="setTodos(...)")
      div(ng-repeat="todo in todos")
          span(contenteditable="true", ng-model="todo.description"){{ todo.description }}

我正在为contenteditable属性定义以下指令:

TodoModule.directive 'contenteditable', ->
  return {} =
    restrict : 'A'
    require: '?ngModel'
    link : (scope, elem, attrs, ngModel) ->
      read = ->
        ngModel.$setViewValue elem.html()
      elem.on 'blur', ->
        scope.$apply read

这是TodoListController的相关部分:

TodoModule.controller 'TodoListController', ($scope, $http) ->
  $scope.update = (todo) ->
    $http.put "/todo/#{todo._id}.json", todo
      .success (data) ->
        if !data.todo
          alert JSON.stringify data

这里的问题是我真的不知道如何在todo链接功能中引用contenteditable对象,以便我可以在contenteditable的模糊事件中调用scope.update(todo)。这可能以某种方式从ngModel作为父母获得吗?

1 个答案:

答案 0 :(得分:0)

这就是我想出的,我并不完全相信这是最好的方式,所以我不会标记答案。

我已经通过父update-on-blur函数向我的jade模板添加了scope.update(todo)属性:

      span(contenteditable, update-on-blur="update(todo)", ng-model="todo.description"){{ todo.description }}

在我的指令中添加了一个隔离范围,然后在模糊触发器中调用了新函数:

TodoModule.directive 'contenteditable', ->
  return {} =
    restrict : 'A'
    require: '?ngModel',
    scope:
      updateOnBlur: '&'
    link : (scope, elem, attrs, ngModel) ->
      console.log scope
      read = ->
        ngModel.$setViewValue elem.html()

      elem.on 'blur', ->
        scope.$apply read
        scope.updateOnBlur()
相关问题