[英]angular share data between controllers and do something with that data and show it in page
我看着这个:
http://www.thinkster.io/pick/9jfpSmbx1j/angularjs-sharing-data-between-controllers
现在尝试调整代码,以便我能进一步了解。
所以这是我做的:
<!doctype html>
<html >
<head>
<script src="http://code.angularjs.org/1.2.8/angular.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="FirstCtrl">
<input type="text" ng-model="data.message">
<h1>{{ data.message }}</h1>
</div>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="data2.length">
<h1>{{ data2.message }}</h1>
</div>
</div>
</body>
</html>
和main.js
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { message: "I'm data from a service" };
});
/*
This Data service can be injected into each of the controllers as a parameter.
By doing this, we are now attaching the data.model to an app service, which repairs
the binding between the two controller models.
*/
function FirstCtrl($scope, Data) {
$scope.data = Data;
}
function SecondCtrl($scope, Data) {
console.log(Data.message.length);
console.log(Data);
$scope.data = Data;
this.getLength = function() {
console.log('called');
return $scope.data.message.length;
}
var data2 = Data;
data2.length = this.getLength();
$scope.data2 = data2;
//$scope.data.length = Data.message.length;
// $scope.data.message = 'a';
}
从日志中我看到this.getLength仅被调用一次。 为什么每次数据更改时都不会调用它? 我想在每个字符串更新更新中更新html中的字符串长度。
更新
固定:
var myApp = angular.module('myApp', []);
myApp.factory('Data', function () {
return { message: "I'm data from a service" };
});
/*
This Data service can be injected into each of the controllers as a parameter.
By doing this, we are now attaching the data.model to an app service, which repairs
the binding between the two controller models.
*/
function FirstCtrl($scope, Data) {
$scope.data = Data;
}
function SecondCtrl($scope, Data) {
$scope.data = Data;
$scope.getLength = function() {
return $scope.data.message.length;
}
var data2 = Data;
$scope.data2 = data2;
data2.length = $scope.getLength();
$scope.$watch(function () {
return $scope.data.message;
},
function (newValue, oldValue) {
if(newValue == oldValue)return; // do nothing if old value equals to old one
data2.length = $scope.getLength();
/****/
}, true);
}
data.message
模型引用input
。 通常,当您在输入字段中键入内容时,真正改变的是data.message
。 但是,如果要在更改时触发其他逻辑,请使用$watch
。 (请参阅此处的 DOCS)
因此,添加到您的代码:
$scope.$watch(function () {
return $scope.data.message;
},
function (newValue, oldValue) {
if(newValue == oldValue)return; // do nothing if old value equals to old one
this.getLength(); // I would use $scope.getLength();
/****/
}, true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.