0

I'm trying to create a directive for on/off button-groups using ui-bootstrap where I bind the ng-model to a $scope value at runtime inside an ng-repeat. It works fine if I add the ng-model directly as an attribute value, but I can't seem to set the ng-model through a directive scope variable.

Here is the example code: http://plnkr.co/edit/RS13ncXIUngdK85AqRWV

html

// directive html markup
<!-- if I set my-ng-model='CFG.debug' in markup it works! -->
<!-- but NOT if I set my-ng-model by script -->
<on-off-switch my-ng-model=""></on-off-switch>

javascript

angular.module(
  'myApp', ['ui.bootstrap'] )
.directive(
  'onOffSwitch', 
  function() {
    var link = function(scope, element, attrs) {
    // $scope.CFG.debug = [true|false]
    // options.switchModel = 'CFG.debug'
    var ngModel;
    ngModel = scope.$parent.options.switchModel;
    if (ngModel !== null) {
      element.attr('my-ng-model', ngModel);
      console.log('ngModel should be='+ngModel)
    }
  };
  return {
    template: 
'<div class="btn-group">\
  <button type="button" class="btn btn-primary" ng-model="myNgModel" btn-radio="false">Off</button>\
  <button type="button" class="btn btn-primary" ng-model="myNgModel" btn-radio="true">On</button>\
</div>',
    restrict: 'AE',
    scope: {
      myNgModel: '='
    },
    link: link
  };
})
michael
  • 4,377
  • 8
  • 47
  • 73
  • I didn't understand your code or what you want to do, but do you know the diference between link phase and compile phase? – Rodrigo Fonseca Feb 09 '14 at 03:45
  • Possible duplicate of http://stackoverflow.com/questions/14115701/angularjs-create-a-directive-that-uses-ng-model If you are inside an ng-repeat, then just bind an ng-model var to each $scope.[x] you are repeating through, and use the above to do so. – ryanlutgen Feb 09 '14 at 07:21
  • I'm trying to bind the model to the 'switch' inside the ng-repeat, but the model is in the form of a string (i.e. "CFG.debug") from a config file. I know this is incorrect, but this is sort of what I'd like to do: $scope.myModel = "CFG.debug" – michael Feb 17 '14 at 17:11
  • @rodrigo I think I need to use $compile to evaluate 'myModel' inside the directive, but I can't figure it out... – michael Feb 17 '14 at 18:36
  • Please refer to this answer, it works great: [AngularJS - Create a directive that uses ng-model](http://stackoverflow.com/questions/14115701/angularjs-create-a-directive-that-uses-ng-model) – Khaldoun Khaled Aug 15 '16 at 10:42

0 Answers0