Abh*_*aye 5 javascript angularjs
我刚开始使用AngularJS,我正在尝试使用工厂在两个ng控制器(两个控制器都在同一个ng-app模块中)之间共享数据.来自controller1的数据(HTML输入字段)似乎在大多数时间与控制器2共享; 但是当我删除输入字段的所有内容时,$ 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>
Run Code Online (Sandbox Code Playgroud)
我发现这个代码还有一个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;
});
});
Run Code Online (Sandbox Code Playgroud)
小提琴:- http://jsfiddle.net/1d1vL1hd/
| 归档时间: |
|
| 查看次数: |
4710 次 |
| 最近记录: |