angular.js - angular自定义指令中如何监视属性值的变化
習慣沉默
習慣沉默 2017-05-15 17:02:48
[AngularJS讨论组]

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的方式无法获取我的数据

習慣沉默
習慣沉默

全部回复(2)
某草草
<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>
仅有的幸福

同志,你的玩法不对哦:

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

<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);
        }
    };
});
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号