【问题标题】:Reference ng-model parent from directive从指令中引用 ng-model 父级
【发布时间】:2014-02-07 17:46:44
【问题描述】:

所以我有以下 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

这里的问题是我真的不知道如何从contenteditable 链接函数中引用todo 对象,以便我可以在contenteditable 的模糊事件中调用scope.update(todo)。这是否可以从 ngModel 作为父级获得?

【问题讨论】:

    标签: angularjs coffeescript pug


    【解决方案1】:

    这是我想出的,但我并不完全相信这是最好的方法,所以我不会标记为已回答。

    我已经向我的玉模板添加了一个update-on-blur 属性,并传递了父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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多