【发布时间】:2015-03-04 16:35:30
【问题描述】:
简单示例:
<body ng-app="testApp">
<form name="myForm" id='CtrlHost' ng-controller="Ctrl">
<input type="Button" value="Change Inside Angular" ng-click="ChangeIt()" />
<input type="Button" value="Change Outside Angular" onclick="OutsideAngularChange()" />
</form>
</body>
angular.module('testApp', [])
.controller('Ctrl', function($scope, MyService) {
var NewPropValue = 1;
$scope.ChangeIt = function () {
alert("scope.changeit called");
NewPropValue++;
MyService.SetMyProp(NewPropValue);
};
$scope.$watch(MyService.GetMyProp, function (newValue) {
alert("NewValue from Watch = " + newValue);
});
}).service('MyService', function () {
var myProp;
this.GetMyProp = function () {
return MyProp;
};
this.SetMyProp = function (newProp) {
MyProp = newProp;
};
});
function OutsideAngularChange() {
alert("OutsideAngularChange called")
angular.element(document.getElementById('CtrlHost')).scope().ChangeIt();
}
http://jsfiddle.net/jonnyknowsbest/4umxanpu/
点击“Change Inside Angular”按钮,触发范围监视。 点击“更改外部角度”按钮,不会触发范围监视。
两个按钮调用相同的作用域方法来更新服务属性。
为什么一个有效而一个无效?
【问题讨论】:
标签: javascript angularjs