HTML код:Может ли кто-нибудь объяснить основную концепцию модели в angularjs?
<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
};
});
Когда я использую, как это то переменная служба не обновляется по обновлению поля ввода.
Может ли кто-нибудь объяснить, почему поведение такое?
имеет любой ответ на ваш вопрос. Пожалуйста, примите это, чтобы стать ссылкой для будущего читателя. – Hisham