在指令角度中访问范围控制器变量

时间:2016-10-27 12:22:26

标签: javascript angularjs angular-directive

我想在指令链接属性中访问范围变量total

即使已触发mouseDown事件的总值正在更新,但$ scope.total没有更改。

以下是代码

功能:将鼠标放在相应的框上时总金额会发生变化



 var app = angular.module("billModule", []);
        app.controller("billController", function ($scope) {
            $scope.total = 0.0;
        });
        app.directive("menu", function ($document) {
            return {
                restrict: "EA",
                replace: true,
                link: function (scope, element, attr) {
                    element.on("mousedown", function () {
                        scope.total += Number(attr.cost);
                      //console.log("total is "+ scope.total);
                    });
                },
                template: function (element, attr) {

                    return "<div class='box' title='$" + attr.cost + "'>" + attr.item + "</div>";
                }
            }
        })
&#13;
.box {
            width: 132px;height: 38px;background-color: red;cursor: pointer;border: groove;text-align: center;padding-top: 5px;font-size: 33px;color: white;
        }
            .box:hover {
                /*background-color: blue;*/
                border: inset;
            }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="billModule">
        <div ng-controller="billController">
            <menu item="Gold" cost="20"></menu>
            <menu item="fruits" cost="40"></menu>
            <menu item="phone" cost="90"></menu>
            <menu item="water" cost="50"></menu>
            <menu item="monitor" cost="70"></menu>
            <div>{{total | currency : '$':2}}</div>
        </div>

    </div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

Angular并不知道这个变化,因为它是使用外部事件处理程序而不是角度事件处理程序(例如ngClick)。要使角度意识到变化,请使用scope.$apply包裹它:

scope.$apply(function() {
    scope.total += Number(attr.cost);
});

如果您使用的是角度1.3或更高版本,请使用scope.$applyAsync,因为它的性能更高一些。

答案 1 :(得分:0)

使用&#39;范围。$ digest();&#39;在&#39; scope.total + = Number(attr.cost);&#39;您的总数将在模板中更新。请参阅下面的plnkr

http://plnkr.co/edit/nOPggwreTTEukYUMbD1X?p=preview

代码:

var app = angular.module("billModule", []);
app.controller("billController", function ($scope) {
    $scope.total = 0.0;
});
app.directive("menu", function ($document) {
    return {
        restrict: "EA",
        replace: true,
        link: function (scope, element, attr) {
            element.on("mousedown", function () {
                scope.total += Number(attr.cost);
                scope.$digest();
              //console.log("total is "+ scope.total);
            });
        },
        template: function (element, attr) {

            return "<div class='box' title='$" + attr.cost + "'>" + attr.item + "</div>";
        }
    }
});