最近接触一个新项目,用到了angularjs,之前对angularjs不熟悉,于是就被坑了,在这里小计一下。
我有两个文件,文件a.html内容如下:
<html>
<head>
<script src='angular.js'></script>
</head>
<body>
<div ng-app="myApp" ng-controller="userCtrl">
<div ng-include="'b.html'"></div>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('userCtrl',function($scope){
$scope.name = 'blakeFez';
$scope.$watch('name',function(){
console.log('change');
});
});
</script>
</body>
</html>
文件b.html内容如下:
<input ng-model='name' type='text'/>
<div>{{name}}</div>
用浏览器打开a.html发现,当我改变name的值时,控制台并没有输出任何东西。
把a.html改成如下:
<html>
<head>
<script src='angular.js'></script>
</head>
<body>
<div ng-app="myApp" ng-controller="userCtrl">
<div>
<input ng-model='name' type='text'/>
</div>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('userCtrl',function($scope){
$scope.name = 'blakeFez';
$scope.$watch('name',function(){
console.log('change');
});
});
</script>
</body>
</html>
这样就可以正常工作了。
后来谷歌的一下,发现,上述问题是由于作用域链问题导致的。使用ng-include引入的东东,里面的变量是在当前scope的child scope中。可以使用如下方法:
把b.html中的变量改成 data.name,在a.html中定义 $scope.data = {name:’linyu’};然后监控 data.name。代码如下:
文件a.html内容如下:
<html>
<head>
<script src='angular.js'></script>
</head>
<body>
<div ng-app="myApp" ng-controller="userCtrl">
<div ng-include="'count.html'"></div>
<input ng-model='data.name2' type='text'/>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('userCtrl',function($scope){
$scope.data = {name:'linyu'};
$scope.$watch('data.name',function(){
console.log('ddd');
});
});
</script>
</body>
</html>
文件b.html内容如下:
<input ng-model='data.name' type='text'/>
<div>{{data.name}}</div>
这样就可以在使用ng-include的情况下,正常监控了。