javascript - 关于angularjs的$watch的使用,以及父子指令之间获取数据的问题
本文介绍了javascript - 关于angularjs的$watch的使用,以及父子指令之间获取数据的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
var app.angular.module('app', []);
app.controller('appController', function($scope) {
var ctrl = this;
if(this.currentValue == "") {
console.log("空字符串");
}
});
app.directive('appDirective', function() {
return {
scope: {},
bindToController: {
currentValue: '=?'
},
controller: 'appController',
controllerAs: 'appCtrl',
link: function(scope, element, attrs, app) {
if(angular.isUndefined(attrs.currentValue)) {
scope.currentValue = "";
}
}
}
});
app.directive('myDirective', function() {
return {
scope: {},
controller: function() {},
controllerAs: 'myCtrl',
require: '^appDirective'
link: function(scope, element, attrs, app) {
//我想在这里监听appDirective里的currentValue的值,但是下面这三种写法都不能实现,应该怎么写watch函数呢?
var watch1 = scope.$watch('app.currentValue', function(){});
var watch2 = scope.$watch('appCtrl.currentValue', function(){});
scope.cv = appCtrl.currentValue;
var watch3 = scope.$watch('cv', function(){});
}
}
})
我想在myDirective里监听appDirective里的值,该怎么写watch函数呢?
在myDirective的HTML模板里使用appCtrl.currentValue及$parent.currentValue的形式都不能获取该值,是为什么呢?
解决方案
把你的
scope.$watch('app.currentValue', function() { /* something */ });
换成
scope.$watch(function() { return app.currentValue; }, function() {
/* something */
})
scope.$watch
的第一个参数可以是字符串也可以是函数。
为函数时监听其返回值。
为字符串时则是监听在当前scope里执行这个expression的结果
在问题的例子里,两个directive都采用了isolated scope,内部directive无法通过scope原形链访问外部directive的scope内容,所以采用字符串参数的scope.$watch
监听不到。
这篇关于javascript - 关于angularjs的$watch的使用,以及父子指令之间获取数据的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文