cari

Rumah  >  Soal Jawab  >  teks badan

angular.js - Bagaimana untuk memantau perubahan dalam nilai atribut dalam arahan tersuai sudut

html

<p on-test data={{userinfo}}></p>
//自定义指令on-test,contorller中通过ajax的方式从后台拿到userinfo,userinfo是一段很长的json字符串,会随着用户的操作而变化

arahan

app.directive('onTest', function () {
    return {
        restrict: 'A',
        scope:{
          test:'@data'
        },
        link: function(scope , element, attr) {
            console.log(scope)
            /**
            *我想在这里拿到后台传过来的userinfo字符串,通过userinfo操作我的dom界面
            **/
        }
    };
});

Ragu saya:

習慣沉默習慣沉默2820 hari yang lalu540

membalas semua(2)saya akan balas

  • 某草草

    某草草2017-05-15 17:04:48

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

    balas
    0
  • 仅有的幸福

    仅有的幸福2017-05-15 17:04:48

    Kawan, permainan anda salah:

    Yang pertama ialah bahagian templat Memandangkan anda ingin memantau perubahan userInfo, ia adalah paling sesuai untuk menggunakan pengikatan dua hala, tetapi apa yang anda tulis ialah atribut yang mengikat (ini tidak cukup keren):

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

    Berikut ialah bahagian pendaftaran arahan:

    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);
            }
        };
    });

    balas
    0
  • Batalbalas