angular.js - angular自定义指令中如何监视属性值的变化
本文介绍了angular.js - angular自定义指令中如何监视属性值的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
html
<div on-test data={{userinfo}}></div>
//自定义指令on-test,contorller中通过ajax的方式从后台拿到userinfo,userinfo是一段很长的json字符串,会随着用户的操作而变化
directive
app.directive('onTest', function () {
return {
restrict: 'A',
scope:{
test:'@data'
},
link: function(scope , element, attr) {
console.log(scope)
/**
*我想在这里拿到后台传过来的userinfo字符串,通过userinfo操作我的dom界面
**/
}
};
});
我的疑惑:
我在link中打印scope,可以看到传递过来的数据,但是通过scope.test的方式无法获取我的数据
解决方案
<div ng-app="app" ng-init="userinfo='123'">
<input type="text" ng-model="userinfo" />{{userinfo}}
<div on-test data="{{userinfo}}"></div>
</div>
<script src="http://cdn.bootcss.com/angular.js/1.5.6/angular.js"></script>
<script>
var app = angular.module('app', [])
app.directive('onTest', function () {
return {
restrict: 'A',
scope: {
test: '@data'
},
link: function (scope, element, attr) {
console.log('init', scope.test)
attr.$observe('data', function (val) {
console.log(val)
})
}
}
})
</script>
这篇关于angular.js - angular自定义指令中如何监视属性值的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文