我刚开始使用AngularJS,并且试图使用工厂在两个ng-controllers之间共享数据(两个控制器都在同一个ng-app模块中)。来自controller1的数据(HTML输入字段)似乎大多数时候都与controller2共享;但是当我删除输入字段的所有内容时,$ watch似乎不起作用!我发现很难用言语解释。以下屏幕截图可能会有所帮助。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<% include ../partials/head %>
</head>
<body class="container" ng-app='myApp'>
<div ng-controller="ctrl1">
<input type="text" ng-model="firstName">
<br>
Input is : <strong>{{firstName}}</strong>
</div>
<div ng-controller="ctrl2">
Input should also be here: {{firstName}}
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
var data = {
FirstName: ''
}
return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (x) {
data.FirstName = x;
}
}
});
myApp.controller('ctrl1', function ($scope, Data) {
$scope.firstName = ''
$scope.$watch('firstName', function(newVal){
if(newVal){Data.setFirstName(newVal);}
});
});
myApp.controller('ctrl2', function ($scope, Data) {
$scope.$watch(function(){return Data.getFirstName();}, function(newVal){
if(newVal){$scope.firstName = newVal;}
});
});
</script>
</body>
<footer>
<% include ../partials/footer %>
</footer>
</html>
我为该代码找到了一个jsfiddle。http://jsfiddle.net/5LL3U/2/
任何帮助表示赞赏。谢谢!
您需要为此同时检查newValue和oldValue。如果newValue为空,它不会调用您的工厂,也不会在变量上设置值。:-
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
var data =
{
FirstName: ''
};
return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (firstName) {
data.FirstName = firstName;
}
};
});
myApp.controller('FirstCtrl', function( $scope, Data ) {
$scope.firstName = '';
$scope.$watch('firstName', function (newValue,oldValue) {
console.log(oldValue+" "+newValue);
if (newValue!=oldValue) Data.setFirstName(newValue);
});
});
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.$watch(function () { return Data.getFirstName(); }, function (newValue,oldValue) {
if (newValue!=oldValue) $scope.firstName = newValue;
});
});
小提琴:-http: //jsfiddle.net/1d1vL1hd/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句