简体   繁体   中英

Ng-model not working for attribute directive

I have a simple controller:

.controller("TestController",['$scope', function($scope) {
    this.p = {};
    this.p.name = "Foo";
    this.p.surname = "Bar";
}]);

And I have a directive calling this controller:

app.directive('cronosDataset',[function() {
  return {
    restrict: 'A',
    controller:'TestController',
    controllerAs: "ctrl",
    scope: {
        cronosDataset : "@"
    }
  };
}])

If I call the controller using ng-controller the ng-model works fine. But if I call it through the directive it doesn't update the view:

<!-- This works -->
Works
<br/>
<div class="sideMenu">
  <form ng-controller="TestController as ctrl">
      Name: <input type="text" ng-model="ctrl.p.name" />
      Surname: <input type="text" ng-model="ctrl.p.surname" />
  </form>
</div>

<!-- This one doesn't work -->
Doesn't work
<br/>
<div class="sideMenu">
  <form cronos-dataset="People">
      Name2: <input type="text" ng-model="ctrl.p.name" />
      Surname2: <input type="text" ng-model="ctrl.p.surname" />
  </form>
</div>

Edit: I can put it to work if I don't use isolated scope ( scope : {...} in directive definition). I'm only using isolated scope to have access to this attribute scope: { cronosDataset : "@" } inside my controller. If there's a different way to do it without use isolated scope then problem solved!

What I'm trying to archive is to reuse the logic I have done to get data from database Example:

<form cronos-dataset="People"><input type="text" ng-model="p.name" /></form>
<form cronos-dataset="Car"><input type="text" ng-model="p.model" /></form>
<form cronos-dataset="Address"><input type="text" ng-model="p.street" /></form>

In my controller I go to database (ajax using cronos-dataset as query parameter) and put the result back in p variable. So i need two things:

1 - Have access to attribute inside the controller
2 - Update the ng-model with a scope variable

Does it make sense?

Here is a PLUNKER

I forked your Plunker to add Transclusion. The Directive Transcludes the element, replacing it entirely. It then takes the cloned (original contents) and inserts them into the Transclusion, making the original elements become compiled as part of the directive.

app.directive('cronosDataset',[function() {
  return {
    restrict: 'A',
    controller:'TestController',
    controllerAs: "ctrl",
    scope: {
        cronosDataset : "@"
    },
    transclude: 'element',
    replace: true,
    link: function(scope, elem, attrs, ctrl, transclude) {
      transclude(scope, function(clone) {
        elem.after(clone);
      });
    }
  };
}])

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