簡體   English   中英

指令角度中的訪問范圍控制器變量

[英]Access scope controller variable in Directive angular

我想在指令鏈接屬性中訪問范圍變量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不知道更改,因為它是使用外部事件處理程序而非角度事件處理程序(例如ngClick)進行的。 要使角度了解更改,請用scope.$apply包裹它:

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

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

使用'scope。$ digest();' 在'scope.total + = Number(attr.cost);'之后 您的總數將在模板中更新。 請參閱下面的plnkr

http://plnkr.co/edit/nOPggwreTTEukYUMbD1X?p=預覽

碼:

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>";
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM