您的位置:首页技术文章
文章详情页

angular.js - angular自定义指令中如何监视属性值的变化

【字号: 日期:2024-10-02 18:58:13浏览:62作者:猪猪

问题描述

html

<p on-test data={{userinfo}}></p>//自定义指令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的方式无法获取我的数据

问题解答

回答1:

<p ng-app='app' ng-init='userinfo=’123’'> <input type='text' ng-model='userinfo' />{{userinfo}} <p on-test data='{{userinfo}}'></p></p><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>回答2:

同志,你的玩法不对哦:

首先是模板部分,既然你想监视userInfo的变化,那用双向绑定的方式最合适不过了,但你写的是绑定属性(这个不够帅):

angular.js - angular自定义指令中如何监视属性值的变化

<p on-test data='userinfo'></p><!--这样就可以了-->

下面是指令注册的部分:

app.directive(’onTest’, function () { return {restrict: ’A’,scope:{ test:’=data’//双向绑定用=},link: function(scope , element, attr) { console.log(scope.test);//high不high?拿到了哦 scope.$watch(’test’, function(newVal){console.log(newVal);//每次你在controller里修改了userInfo,这里都会打印 }, true);} };});

相关文章: