请检查这个jsFiddle:
http://jsfiddle.net/mystikacid/b7hqcdfk/4/
模板:
<div ng-app="myApp">
<div ng-controller="dataCtrl">
<div>Data : {{data}} (Value outside views)</div>
<div ng-include src="view"></div>
<script type="text/ng-template" id="view1">
<p> View 1 </p>
<p>Value inside view 1 : {{data}}</p>
<input type = "text" ng-model = "data" />
<button ng-click = 'changeView("view2")' > Go to view 2 </button>
</script>
<script type="text/ng-template" id="view2">
<p> View 2 </p>
<p>Value inside view 2 : {{data}}</p >
<input type = "text" ng-model = "data" />
<button ng-click = 'changeView("view1")' > Go to view 1 </button>
</script>
</div>
</div>
JavaScript的:
var myApp = angular.module('myApp', []);
myApp.factory('myFactory', function () {
var factory = {};
factory.data = 'Default data';
return factory;
});
myApp.controller('dataCtrl', function ($scope, myFactory) {
$scope.view = 'view1';
$scope.data = myFactory.data;
$scope.changeView = function (view) {
$scope.view = view;
}
});
有两个问题:
1。为什么输入文本时外部视图中显示的数据不会改变?
2。如果我输入一些文本并转到视图2,为什么输入框和view2中的数据会被重置?
请帮助我理解这种行为,谢谢。
答案 0 :(得分:2)
您直接绑定到基本类型(在您的情况下是String)。这在AngularJS中效果不佳...请查看answer;
改为使用模型对象:
myApp.factory('myFactory', function () {
var factory = {};
factory.model = {
data: 'Default data'
};
return factory;
});
myApp.controller('dataCtrl', function ($scope, myFactory) {
...
$scope.model = myFactory.model;
...
});
关于意见:
<input type = "text" ng-model = "model.data" />