指令中的访问范围控制器变量 angular

Access scope controller variable in Directive angular

我想在指令 link 属性.

中访问范围变量 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>";
                }
            }
        })
.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;
            }
<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>

Angular 不知道更改,因为它是使用外部事件处理程序进行的,而不是 angular 事件处理程序(例如 ngClick)。要让 angular 知道更改,请用 scope.$apply:

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

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

在 'scope.total += Number(attr.cost);' 之后使用 'scope.$digest();' 您的总数将在模板中更新。参考下面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>";
        }
    }
});