2014-02-07 76 views
0

所以我有以下玉模板:參考NG-模型父

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作爲父母獲得?

回答

0

這是我想到的,我並不完全相信這是最好的方式,所以我不會標記回答。

我添加了一個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()