国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

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

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

瀏覽:179日期: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);} };});

相關文章:
主站蜘蛛池模板: 招远市| 通河县| 汨罗市| 城固县| 高州市| 万荣县| 贺兰县| 林周县| 内乡县| 正蓝旗| 望城县| 阜新市| 天全县| 新晃| 平湖市| 康定县| 威宁| 洛川县| 微博| 芦山县| 青川县| 九寨沟县| 蒙城县| 泰来县| 武定县| 麦盖提县| 高尔夫| 山东| 德令哈市| 工布江达县| 江源县| 普安县| 门源| 和龙市| 邻水| 富顺县| 珠海市| 墨玉县| 来宾市| 资兴市| 庆云县|