Dav*_*ong 5 javascript angularjs angularjs-scope
我的Angular应用中有一个控制器:
(function (angular) {
function MyController() {
this.name = 'Dave';
// I want to have code like this:
/*
$scope.$watch('name', function (newValue, oldValue) {
console.log(oldValue, "changed to", newValue);
});
*/
}
window.myApp = angular.module('myApp', [])
.controller('MyController', [MyController]);
})(angular);
Run Code Online (Sandbox Code Playgroud)
$scope.$watch将值附加到MyController原型时,是否可以使用的功能?
我确实在代码中注意到,如果我添加类似的内容ng-controller="MyController as myCtrl",并将$scope.$watch语句更改为$scope.$watch('myCtrl.name', ...),则在添加$scope依赖项后它会起作用,但这就像将控制器绑定到我的视图一样,这是错误的。
编辑
试图澄清我的要求。我的HTML是这样的:
<div ng-app="myApp">
<div ng-controller="MyController as myCtrl">
<input type="text" ng-model="myCtrl.name" />
<p>{{myCtrl.helloMessage}}</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我的控制器是这样的:
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
this.name = 'World';
this.helloMessage = "Hello, " + this.name;
var self = this;
$scope.$watch('myCtrl.name', function () {
self.helloMessage = "Hello, " + self.name;
});
}]);
Run Code Online (Sandbox Code Playgroud)
这目前可行,但是如您所见,在$watch通话中,我必须通过controllerAs从我的观点中名称,这并不理想。
我在Plunkr上设置了一个示例
在每个 $digest 周期上计算的表达式。返回值的更改会触发对侦听器的调用。监视表达式可以是字符串或函数。
- 字符串:作为表达式求值
- function(scope):以当前范围作为参数调用。
angular.module('app', []).controller('MainCtrl', function($scope) {
this.name = 'World'
this.helloMsg = ''
$scope.$watch(function() {
return this.name
}.bind(this), function(newName) {
this.helloMsg = "Hello, " + newName
}.bind(this))
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app'>
<div ng-controller='MainCtrl as ctrl'>
<input type='text' ng-model='ctrl.name' />
{{ ctrl.helloMsg }}
</div>
</div>Run Code Online (Sandbox Code Playgroud)