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

时间:2016-06-06 20:56:30

标签: javascript angularjs angularjs-directive angularjs-scope

我有一个条件,我在列表网格中有输入框,我有一个指令,现在我想将值发送到此指令,输入值是什么......到此为止它的工作正常,但是现在,当我尝试更改指令输入框中的值时,它不会更新列表网格输入框,其值为指令集。

这是一个有效的工作人员,让我知道我做错了什么。

http://plnkr.co/edit/DZdN4itTNccVsuBEJahr?p=preview

我的controller& directive代码就像 -

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) {

    }
  };
})

3 个答案:

答案 0 :(得分:2)

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

然后testdir需要知道来自item的哪个字段用作模型值。例如,让我们使用帮助器属性:

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

最后在指令模板中,您需要绑定到directivevalue[field]

<input type="text" ng-model="directivevalue[field]" />

演示http://plnkr.co/edit/jWKwDJvYOutcLihi7UyC?p=preview

答案 1 :(得分:1)

检查此工作plnkr -

http://plnkr.co/edit/DZdN4itTNccVsuBEJahr?p=preview

指令代码 -

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以跟踪值更改为指令 -

<input ng-model="item.age" ng-click="vm.fordirective = item.age; vm.index = $index" ng-change="vm.fordirective = item.age; vm.index = $index" />

答案 2 :(得分:0)

而不是使用$ parent(因为它不是一个好习惯),因为angular本身处理双向数据绑定非常顺利。

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

检查work plunkr:

https://embed.plnkr.co/LyE0G0APhwC4nco1KvOw/

指令代码:

scope.setParentValue = function(directivevalue){ scope.directivevalue = directivevalue; };

相关问题