HTML代码:
<mydirective></mydirective>
<input type="button" ng-click="showText()" value="Show Service Text" />Js代码:
var app = angular.module('demo', []);
app.service('myService', function () {
var text = { id: 1, value: 'hello' };
this.getText = function () {
return text;
}
});
app.controller('demoController', ['$scope', 'myService', function ($scope, myService) {
$scope.showText = function () {
alert(myService.getText().value);
}
}]);现在,我将展示我的指令的两个版本:
1)第一个版本:
app.directive('mydirective', function () {
var controller = ['$scope', 'myService', function ($scope, myService) {
$scope.randomtext = myService.getText();
}];
var template = '<div><input type="text" ng-model="randomtext.value" /><span ng-bind="randomtext.value"></span></div>'
return {
restrict: 'E',
scope: {},
controller: controller,
template: template
};
});当我像这样使用时,服务变量将在更新输入字段时更新。
2)第二个版本:
app.directive('mydirective', function () {
var controller = ['$scope', 'myService', function ($scope, myService) {
$scope.randomtext = myService.getText().value;
}];
var template = '<div><input type="text" ng-model="randomtext" /><span ng-bind="randomtext"></span></div>'
return {
restrict: 'E',
scope: {},
controller: controller,
template: template
};
});当我像这样使用时,那么服务变量在更新输入字段时不会更新。
有没有人能解释为什么行为是这样的?
发布于 2015-12-27 23:58:15
这是一个Javascript问题,而不是一个AngularJS问题。您在区分引用类型值和原始类型值时遇到了问题。
下面的例子应该可以消除误解:
var myObject = {
value: 1
};
var $scope = {};
$scope.data = myObject;
$scope.data.value = 3;
// This should alert the value of 3
window.alert(myObject.value);
上面的代码片段应该会警告3的值,因为您正在更改传递给$scope.data的myObject的reference值。
检查下面的例子,它应该会告诉你原始值不是以这种方式工作的。
var myObject = { value: 1 };
var $scope = {};
$scope.data = myObject.value;
$scope.data = 3;
// This should alert the value of 1
window.alert(myObject.value);
发布于 2015-12-28 00:02:35
第一版(工作版本)
$scope.randomtext = myService.getText();这使得$scope.randomtext成为对服务中相同文本对象的引用,因此,每当使用您的输入字段更改$scope.randomtext时,服务中的文本对象也将更改,并且当您向其发出警报时,您将获得更新值。
第二版(不起作用的那个版本)
$scope.randomtext = myService.getText().value;在这个版本中,$scope.randomtext不是对text对象的引用,赋值操作符在$scope.randomtext中创建了一个新的value属性副本,使它成为一个全新的变量,它与服务没有任何联系,所以每当你在输入字段中更改随机文本时,myservice中的对象都不会感觉到任何东西。
https://stackoverflow.com/questions/34481540
复制相似问题