【发布时间】:2016-04-01 14:17:42
【问题描述】:
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);
}
}]);
现在,我将展示我的指令的 2 个版本:
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
};
});
当我这样使用时,服务变量不会在更新输入字段时更新。
谁能解释为什么会这样?
【问题讨论】:
-
有任何答案回答您的问题。请接受它以成为未来读者的参考。
标签: angularjs angularjs-directive angularjs-scope angularjs-service angular-directive