angular.js - How to monitor changes in attribute values ​​in angular custom directives
習慣沉默
習慣沉默 2017-05-15 17:02:48
0
2
534

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

My doubts:

  • I print the scope in the link and can see the passed data, but I cannot get my data through scope.test

習慣沉默
習慣沉默

reply all(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>
仅有的幸福

Comrade, your gameplay is wrong:

First is the template part. Since you want to monitor the changes of userInfo, it is most suitable to use two-way binding, but what you write is binding attributes (this is not cool enough):

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

The following is the command registration part:

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);
        }
    };
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template