2014-02-18 71 views
1

我试图通过单击指令模板中的编辑锚来改变输入指令中的ng模型。通过指令更改ng模型

函数f()假设访问外部控制器并将editableValue绑定到名称或公司,以便通过输入更改它。

输入确实显示个人值,但它不绑定到它。

<p edit="person.name"></p> 
<p edit="person.company"></p> 
<input ng-model="editableValue"> 

main.controller('editsCtrl', function($scope){ 
    $scope.setToEdit = function(val){ 
     $scope.editableValue = val; 
    } 
}); 

main.directive('edit', function(){ 
return{ 
    template:'{{edit}}<a ng-click="f()"> Edit </a>', 
    restrict:'A', 
    scope:{ 
     edit:"=" 
    }, 
    replace:false, 

    link: function(scope, element, attrs, ctrl) { 
      scope.f = function(){ 
        scope.$parent.setToEdit(scope.edit); 
      } 
      } 
    } 
}) 

即使我这样做,它不绑定,只是值传递:

scope.$parent.editableValue = scope.$parent.person.name; 

对于新手这成为有点混乱,我失去了什么?

回答

0

范围分配失败在这里:

scope.f = function(){ 
        scope.$parent.setToEdit(scope.edit); 
      } 

因为你的范围有限的位置:

scope:{ 
     edit:"=" 
    }, 

编辑是唯一范围父母会看到,因为你已经设置双向绑定就可以使用“= '

+0

Ty,这不是唯一的问题,它真的不必像这样绑定,如果我可以做一些像ng-model =“editableValue ['someproperty']”,并根据链接设置$ scope.someproperty ttr值(在课程点后)或similliar,它会工作得很好。尝试了很多变体,例如“currentPerson ['{{someproperty}}']”,并且在$ directive内部尝试了试验... – Koango