简体   繁体   中英

Change controller scope value from directive AngularJS

I have a condition in which I have input boxes in listing grid and I have a single directive, now I want to send the value to this directive what ever the input value is..up to this point its working fine, but now when I am trying to change the value from directive input box it is not updating the list grid input box for which the value to the directive set.

Here is a working plnkr, let me know what I am doing wrong.

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

My controller & directive code is like -

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

    }
  };
})

You could set up vm.fordirective to be object reference to item :

Then testdir would need to know somehow what field from item to use as model value. For example, let's use helper attribute:

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

And finally in directive template you need to bind to directivevalue[field] :

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

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

Check this working plnkr -

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

Directive Code -

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;
      };
    }
  };
})

and in Grid list input, add ng-change to track value change to directive -

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

Instead of using $parent(as it is not a good practice) because angular is handle two way data binding very smoothly itself.

To do this you can bind complete item with the directive scope.

Check working plunkr:

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

Directive code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM