angular.js - angular自定義指令中如何監(jiān)視屬性值的變化
問題描述
html
<p on-test data={{userinfo}}></p>//自定義指令on-test,contorller中通過ajax的方式從后臺(tái)拿到userinfo,userinfo是一段很長(zhǎng)的json字符串,會(huì)隨著用戶的操作而變化
directive
app.directive(’onTest’, function () { return {restrict: ’A’,scope:{ test:’@data’},link: function(scope , element, attr) { console.log(scope) /** *我想在這里拿到后臺(tái)傳過來的userinfo字符串,通過userinfo操作我的dom界面 **/} };});
我的疑惑:
我在link中打印scope,可以看到傳遞過來的數(shù)據(jù),但是通過scope.test的方式無法獲取我的數(shù)據(jù)
問題解答
回答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:
同志,你的玩法不對(duì)哦:
首先是模板部分,既然你想監(jiān)視userInfo的變化,那用雙向綁定的方式最合適不過了,但你寫的是綁定屬性(這個(gè)不夠帥):

<p on-test data='userinfo'></p><!--這樣就可以了-->
下面是指令注冊(cè)的部分:
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,這里都會(huì)打印 }, true);} };});
相關(guān)文章:
1. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. css - 寫頁(yè)面遇到個(gè)布局問題,求大佬們幫解答,在線等,急!~4. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務(wù)器還是不能訪問?5. javascript - 移動(dòng)端上不能實(shí)現(xiàn)拖拽布局嗎?6. 實(shí)現(xiàn)bing搜索工具urlAPI提交7. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化8. phpstudy8.1支持win11系統(tǒng)嗎?9. 配置Apache時(shí),添加對(duì)PHP的支持時(shí)語法錯(cuò)誤10. javascript - nodejs關(guān)于進(jìn)程間發(fā)送句柄的一點(diǎn)疑問

網(wǎng)公網(wǎng)安備