首页 > angular自定义指令中如何监视属性值的变化

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界面
            **/
        }
    };
});

我的疑惑:


<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>

同志,你的玩法不对哦:

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

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

下面是指令注册的部分:

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);
        }
    };
});
【热门文章】
【热门文章】