当前位置: 动力学知识库 > 问答 > 编程问答 >

Can anyone explain the core concept of model in angularjs?

问题描述:

HTML Code:

<mydirective></mydirective>

<input type="button" ng-click="showText()" value="Show Service Text" />

Js Code:

 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);

}

}]);

Now, I will show the 2 versions of my directive:

1) First Version:

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

};

});

Fiddle Link

When I use like this then the service variable is updated on updating the input field.

2) Second Version:

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

};

});

Fiddle Link

When I use like this then the service variable is not updated on updating the input field.

Can anyone explain why the behaviour is like this?

网友答案:

This is a Javascript problem not an AngularJS problem. You're having problems with differentiating between a reference type value and a primitive type value.

The example below should clear the misunderstanding:

var myObject = {
  value: 1
};

var $scope = {};

$scope.data = myObject;

$scope.data.value = 3;

// This should alert the value of 3
window.alert(myObject.value);
网友答案:

First version (The working one)

$scope.randomtext = myService.getText();

This makes $scope.randomtext a reference to the same text object in your service, so whenever $scope.randomtext is changed with your input field, the text object in the service will also change and you get the updated value when you alert it.

Second version (The one that is not working)

$scope.randomtext = myService.getText().value;

in this version $scope.randomtext is NOT a reference to the text object, the assignment operator creates a new copy of the value property into $scope.randomtext, making it a totally new variable that is not tied in any way with the service, so whenever you change randomtext in your input field, the object in myservice will not feel a thing.

分享给朋友:
您可能感兴趣的文章:
随机阅读: