Javascript 从指令AngularJS更改控制器范围值

Javascript 从指令AngularJS更改控制器范围值,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,我有一个条件,在列表网格中有输入框,我有一个指令,现在我想把值发送给这个指令,不管输入值是什么。到目前为止,它工作正常,但现在,当我试图更改指令输入框中的值时,它并没有更新为指令设置值的列表网格输入框 这是一个工作plnkr,让我知道我做错了什么 我的控制器&指令代码如下- var myApp = angular.module('myApp', []); myApp.controller('mainCtrl', function(){ var vm = this; vm.fordi

我有一个条件,在列表网格中有输入框,我有一个指令,现在我想把值发送给这个指令,不管输入值是什么。到目前为止,它工作正常,但现在,当我试图更改指令输入框中的值时,它并没有更新为指令设置值的列表网格输入框

这是一个工作plnkr,让我知道我做错了什么

我的
控制器
&
指令
代码如下-

var myApp = angular.module('myApp', []);

myApp.controller('mainCtrl', function(){
  var vm = this;

  vm.fordirective = '';

  vm.list = [
    {id: "1", name: 'Test 1', age: 35},
    {id: "2", name: 'Test 2', age: 36},
    {id: "3", name: 'Test 3', age: 37},
    {id: "4", name: 'Test 4', age: 38},
  ];
})

myApp.directive('testdir', function(){
  return {
    restrict: 'EA',
    scope: {
      directivevalue: "="
    },
    templateUrl: 'dirtemplate.html',
    link: function(scope, elem, attrs) {

    }
  };
})

您可以将
vm.fordirective
设置为
项的对象引用

然后,
testdir
需要知道从
item
中使用哪个字段作为模型值。例如,让我们使用helper属性:

<testdir directivevalue="vm.fordirective" field="age">Loading..</testdir>

演示

检查此工作plnkr-

指令码-

myApp.directive('testdir', function(){
  return {
    restrict: 'EA',
    scope: {
      directivevalue: "=",
      index: "="
    },
    templateUrl: 'dirtemplate.html',
    link: function(scope, elem, attrs) {

      scope.setParentValue = function(directivevalue){
        scope.$parent.vm.list[scope.index].age = directivevalue;
      };
    }
  };
})
在网格列表输入中,添加
ng change
,以跟踪指令的值更改-

而不是使用$parent(因为这不是一个好的做法),因为angular本身可以非常平滑地处理双向数据绑定

为此,可以将完整项与指令范围绑定

检查工作状态:

指令代码:

scope.setParentValue=函数(directivevalue){
scope.directivevalue=directivevalue;
};

我想你没有抓住重点。或者我没抓住重点。一旦开始编辑不在循环中的输入,绑定将被破坏。尝试单击循环中的输入,然后在“testdir”中编辑输入,然后单击循环中的另一个输入。@dfsq不起作用。.假设您单击了列表中的第二个输入。.然后它将显示具有第二个输入值的指令。.现在更改指令输入值,您将看到网格列表中的第二个输入值不起作用change@TechSolvr你是对的,我误解了。通过正确的演示来检查正确的版本。通过在指令链接功能中硬编码
age
,您使它变得非常突兀和不灵活。例如,如果不编辑指令,您不能将其与不同的属性名称一起使用。@dfsq是的,我同意这可能不是最好的代码。.但在这种情况下,更改不会太痛苦,因为即使我将年龄作为一个属性传递给指令,那么在更改的后期,我需要更改thr本身
myApp.directive('testdir', function(){
  return {
    restrict: 'EA',
    scope: {
      directivevalue: "=",
      index: "="
    },
    templateUrl: 'dirtemplate.html',
    link: function(scope, elem, attrs) {

      scope.setParentValue = function(directivevalue){
        scope.$parent.vm.list[scope.index].age = directivevalue;
      };
    }
  };
})