如何从我的案例中获取指令的值

时间:2014-07-02 20:48:24

标签: javascript html angularjs

我正在尝试在Angular中为我的应用创建一个指令,并且需要将值传递给我的控制器

我有类似

的东西
controllers.directive('checkBox', function() {
    return {
        restrict: 'E',
        scope: {
            checkAll: '=',
        },
        template: '<input check-all="checkAll" type="checkbox" ng-model="check"/>',
        replace: true,
        link: function(scope) {
            scope.$watch('checkAll', function(newVal){
                scope.check = newVal;
            })
        }
    }
})

app.controller('test', function(){
    $scope.submit=function(){
    //not sure how to get the checkbox value as $scope.check is undefined....        
    }
})

HTML

<div ng-controller="test">
 <div class="checkbox" ng-repeat="item in items">
      <check-box></check-box>{{item.name}}
 </div>
  <button type="button" ng-click="submit()">submit</button
</div>

1 个答案:

答案 0 :(得分:2)

您正在使用= checkAll进行双向绑定。

scope: {
    checkAll: '=',
}

这就是你这样做的方式。基本上,您的指令将具有check-all属性以及从控制器视图传递给它的任何$scope变量,您可以在指令中修改该变量,并且该值将反映在控制器中。< / p>

例如,假设您的控制器有一个名为testValue的范围变量。然后你就可以在标记中使用它:

<div class="checkbox" ng-repeat="item in items">
    <check-box check-all="testValue"></check-box>{{item.name}}
</div>

现在指令的链接功能中checkAll指令所做的任何内容都会反映在控制器的$scope.testValue中。

因此,如果您希望控制器中的某个其他变量获得不同的值,只需为您的指令添加另一个属性,例如checkAll,它就可以完成这项工作。

希望有所帮助。

更新:

我正确阅读了你的代码,我想我知道你需要什么。让我试着为你做点什么。

controllers.directive('checkBox', function() {
    return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            checkAll: '='
        },
        template: '<input check-all="checkAll" type="checkbox" ng-model="ngModel"/>',
        replace: true,
        link: function(scope) {
            scope.$watch('checkAll', function(newVal){
                scope.check = newVal;
            })
        }
    }
})

app.controller('test', function(){
    $scope.submit=function(){
      console.log($scope.checkboxVariable);
      // or use $http service to send the value
    }
})

HTML

<div ng-controller="test">
  <div class="checkbox" ng-repeat="item in items">
    <check-box ng-model="checkboxVariable"></check-box>{{item.name}}
  </div>
  <button type="button" ng-click="submit()">submit</button
</div>

让我解释一下。

我认为你想要的是你的指令取代了复选框输入元素。检查时,必须设置范围内的某些内容。除非允许在控制器范围内设置值,否则该指令不能设置任何内容。这可以通过使用=设置使用双重绑定来实现。因此,我们使用双重绑定定义了一个名为ngModel的新范围属性。在标记中,我们传递一个名为check的范围变量。现在,当选中/取消选中输入复选框时,指令的范围将在其自己的范围ngModel变量上获取其值。由于ngModel具有双重绑定,因此它会反映在控制器的check变量中。

希望这有帮助。

相关问题