[英]Access scope controller variable in Directive angular
I want to access Scope variable total
in directive link property. 我想在指令链接属性中访问范围变量
total
。
Even though total value is updating on mouseDown event was fired, but the $scope.total was not changing. 即使触发了mouseDown事件时总值正在更新,但$ scope.total仍未更改。
Here is the code 这是代码
functionality: Total amount changes when mouse down on respective boxes 功能:将鼠标移到相应的框上时,总量发生变化
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 is not aware of the change, since it was made using an external event handler, and not an angular event handler (ngClick for example). Angular不知道更改,因为它是使用外部事件处理程序而非角度事件处理程序(例如ngClick)进行的。 To make angular aware of the change, wrap it with
scope.$apply
: 要使角度了解更改,请用
scope.$apply
包裹它:
scope.$apply(function() {
scope.total += Number(attr.cost);
});
If you're using angular 1.3 or above, use scope.$applyAsync
, as it's a bit more performant. 如果您使用的是angular 1.3或更高版本,请使用
scope.$applyAsync
,因为它的性能更高。
Use 'scope.$digest();' 使用'scope。$ digest();' after 'scope.total += Number(attr.cost);'
在'scope.total + = Number(attr.cost);'之后 your total will gets updated in the template.
您的总数将在模板中更新。 Refer below plnkr
请参阅下面的plnkr
http://plnkr.co/edit/nOPggwreTTEukYUMbD1X?p=preview http://plnkr.co/edit/nOPggwreTTEukYUMbD1X?p=预览
Code: 码:
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.