在运行时设置ng-model的角度指令(即在ng-repeat内部)

时间:2014-02-09 02:23:05

标签: angularjs angular-ui-bootstrap

我正在尝试使用ui-bootstrap为on / off按钮组创建一个指令,其中我在ng-repeat内的运行时将ng-model绑定到$ scope值。如果我将ng-model直接添加为属性值,它可以正常工作,但我似乎无法通过指令范围变量设置ng-model。

以下是示例代码: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
  };
})

0 个答案:

没有答案