设置角度指令的初始模型值

时间:2014-11-22 17:10:49

标签: angularjs

我有一个指令:

<div class="my-switch-on-off" 
     data-caption="Back" 
     data-section="frames" 
     data-module="back"
     >
</div>

它的模板是一个复选框:

<input type="checkbox" class="switch"
  ng-model="isActive"
  ngTrueValue="true"
  ngFalseValue="false"
  ng-change="toggleVisibility(section, module)"
/>

该指令大约使用了10次。不检查所有复选框。我想在我的链接功能中有一个条件,所以我可以检查一些它们。这样做的正确方法是什么?我应该访问模型并更改其值,还是应该使用jQuery lite检查复选框?我的指示如下:

angular.directive("mySwitchOnOff", [
  function() {
    return {
      restrict: "C",
      scope: {},
      templateUrl: "template.html",
      link: function(scope, element, attrs) {
        return scope.toggleVisibility = function(section, module) {

        };
      }
    };
  }
]);

更新,jsfiddle thx到@deitch 我想要的是当数据部分= extensions时要检查的模板的复选框 http://jsfiddle.net/m0q28vjc/2/

1 个答案:

答案 0 :(得分:1)

哦,肯定会在范围内设置ng-model的值。

在你的指令

angular.directive("mySwitchOnOff", [
  function() {
    return {
      restrict: "C",
      scope: {},
      templateUrl: "template.html",
      link: function(scope, element, attrs) {
        // set the value of toggled based on attrs
        scope.isActive = attrs.section === "extensions";
        return scope.toggleVisibility = function(section, module) {

        };
      }
    };
  }
]);

这是一个结构正确的小提琴

http://jsfiddle.net/m0q28vjc/4/