【问题标题】:Access $scope variable inside directive template and update controller $scope.variable访问指令模板内的 $scope 变量并更新控制器 $scope.variable
【发布时间】:2015-04-21 17:58:22
【问题描述】:

我创建了一个带有输入元素和跨度的简单指令。使用该指令,我创建了两个具有隔离范围的自定义元素。现在,我正在尝试获取在指令的输入元素中输入的数据的总和。但真的不知道该怎么做。 这是我的控制器和指令:

angular.module('mapp',[])

.controller('ctrl',['$scope',function($scope){
    $scope.total = 0;  
}])

.directive('customElement',function(){
    return {
        restrict: 'E',
        scope:{
            data: '=info'
        },
        template: '<input type="text" ng-model="data1">\
                    <span>{{data1}}</span>'
    }
});

我希望总结所有指令元素的 data1 并更新 $scope.total。这是 HTML 代码:

<div ng-app="mapp">
    <div ng-controller="ctrl">

        <custom-element info="a"></custom-element>
        <custom-element info="b"></custom-element>
        <br/>
        <br/> Total: <span>{{total}}</span>
    </div>
</div>

这是DEMO

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    Total: &lt;span&gt;{{a+b}}&lt;/span&gt; 这也可以在 html 中使用,而无需使用 $watch 或控制器中的函数

    【讨论】:

      【解决方案2】:

      这是你可以用 $watch 做的事情

      控制器

      .controller('ctrl',['$scope',function($scope){
          $scope.test = {};
          $scope.test.a = 0;
          $scope.test.b = 0;
          $scope.$watch('test',function(newVal,oldVal){
              $scope.total = $scope.test.a + $scope.test.b
          },true)
          $scope.total = 0;
      }])
      

      指令将ng-model="data1"更改为ng-model="data"

      template: '<input type="number" ng-model="data">\
                          <span>{{data}}</span>'
      

      Working Fiddle

      【讨论】:

        【解决方案3】:

        Here 是一个工作小提琴

        angular.module('mapp', [])
        
            .controller('ctrl', ['$scope', function ($scope) {
            $scope.total = 0;
            $scope.a = 0;
            $scope.b = 0;
            $scope.$watchCollection('[a,b]', function () {
                console.log('watch');
                $scope.total = $scope.a + $scope.b;
            });
        }])
        
            .directive('customElement', function () {
            return {
                restrict: 'E',
                scope: {
                    data: '=info'
                },
                template: '<input type="number" ng-model="data">\
                            <span>{{data}}</span>'
            }
        });
        

        A version without $watch

        A version with ng-repeat

        【讨论】:

        • 太棒了!!它完成了这项工作。还有一个疑问。如果指令是循环动态创建的,还有办法实现上述功能吗?
        • 动态创建是什么意思? ng重复?
        • 添加了演示 ng-repeat 的版本
        猜你喜欢
        • 2017-05-14
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2016-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-06
        相关资源
        最近更新 更多