所有
现在,我正在学习AngularJS指令,为了简单的试用目的,我写了一个小脚本:
<html ng-app="vp">
<head>
<title>try container</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css" />
</head>
<body ng-controller="dashboard">
<testscope info="info.name"></testscope>
<script type="text/javascript" src="jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.15/angular-route.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.10/d3.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
var app = angular.module("vp", []);
app.controller("dashboard",["$scope", function($scope){
$scope.info = {
name:"scope",
value:"scopevalue"
};
$scope.$on("showcontrollerscope", function(){
console.log("scope in controller:", $scope.info.name);
});
$scope.$watch("info", function(newn, oldn){
console.log("after change", $scope.info.name);
}, true);
}]);
app.directive("testscope", function(){
return {
restrict: "AE",
scope:{
info: "="
},
controller: function($scope, $element, $attrs){
console.log($scope);
$scope.$emit("showcontrollerscope");
$scope.info = "changed scope";
$scope.$emit("showcontrollerscope");
}
};
});
</script>
</body>
</html>
我的问题是为什么输出上的$是范围而不是范围和更改范围?就像在$ watch中一样。
我原本认为$ emit是asyn,但是有人说它是同步的 它们是同步的。
另见https://groups.google.com/d/msg/angular/yyH3FYAy5ZY/APANNMnolD8J
我发现很多人建议不要在控制器中使用$ watch,那我怎么能这样做呢?
由于