javascript - ng-include : How can I maintain data in $scope after changing views? -
please check jsfiddle:
http://jsfiddle.net/mystikacid/b7hqcdfk/4/
template:
<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 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 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; } });
there 2 issues :
1 . why data displayed outside views not change on entering text?
2 . if enter text , go view 2, why data in input box , view2 reset ?
please me understand behaviour, thanks.
you binding directly primitive types (in case string). doesn't work in angularjs... check answer;
use model object instead:
myapp.factory('myfactory', function () { var factory = {}; factory.model = { data: 'default data' }; return factory; }); myapp.controller('datactrl', function ($scope, myfactory) { ... $scope.model = myfactory.model; ... });
and on views:
<input type = "text" ng-model = "model.data" />
Comments
Post a Comment