久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

angular.js - angular自定義指令中如何監視屬性值的變化

瀏覽:174日期:2024-10-02 18:58:13

問題描述

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

相關文章:
主站蜘蛛池模板: 绥芬河市| 阳西县| 莱芜市| 巴南区| 都匀市| 四川省| 潼关县| 思南县| 海安县| 吴忠市| 德惠市| 宜兴市| 罗山县| 武乡县| 泰宁县| 英德市| 乌拉特中旗| 宣城市| 宜川县| 隆尧县| 天门市| 区。| 张北县| 崇阳县| 丰顺县| 佛坪县| 鹤庆县| 平利县| 景东| 内丘县| 扶绥县| 雅安市| 汝城县| 临澧县| 祁阳县| 唐山市| 广安市| 广南县| 蒙城县| 报价| 博罗县|