AngularJS:从HTML中的数据初始化模型?
发布时间:2020-12-17 06:46:35 所属栏目:安全 来源:网络整理
导读:我正在考虑尝试从 HTML中的数据初始化(部分)AngularJS模型,而不是向服务器请求将数据作为 JSON获取,或者直接在页面中嵌入JSON对象. (服务器目前只用HTML(而不是JSON)呈现数据,我现在想避免重写“太多”代码,而且HTML适用于搜索引擎. 应用程序本身是一个讨论
我正在考虑尝试从
HTML中的数据初始化(部分)AngularJS模型,而不是向服务器请求将数据作为
JSON获取,或者直接在页面中嵌入JSON对象.
(服务器目前只用HTML(而不是JSON)呈现数据,我现在想避免重写“太多”代码,而且HTML适用于搜索引擎. 下面是我的HTML(简化)示例.其中嵌入的数据是帖子ID(123456),作者ID(789),作者姓名(Kitty霸主)和文本消息(“Kittens Cats!Just kidding.”). <div id="post-123456"> <div class="dw-p-hd"> By <span data-dw-u-id="789">Kitty overlord</span> </div> <div class="dw-p-bd"> <p>Kittens</p><p><strike>Cats! Just kidding.</strike></p> </div> </div> 我想构建一个AngularJS控制器,并将$scope初始化为: $scope = { postId = 123456,authorId = 789,text = 'Kittens ....',} 也许我可以像这样使用ng-init: <div id="post-123456" ng-controller="CommentCtrl" ng-init="{ postId =...,authorId =...,text =... }"> <--- look here <div class="dw-p-hd"> By <span data-dw-u-id="789">Kitty overlord</span> </div> <div class="dw-p-bd"> <p>Kittens...</p> </div> </div> 但后来我要发送两次数据:一次在ng-init中,一次在HTML中.我想我不得不以某种方式跳过ng-init属性. 无论如何你认为这是一个好的方法吗? 有没有办法避免两次包含数据? (在html和ng-init中都有) 解决方法
似乎将所有这些数据存储在json中会更好:
//... posts: [ { postId : 123456,authorId : 789,text : 'Kittens ....' },{ postId : 123457,authorId : 790,text : 'Puppies....' } ] //... 然后用ng-repeat填充它,如: <div ng-repeat="post in posts" id="{{post.postId}}" ng-controller="CommentCtrl" > <div class="dw-p-hd"> By <span data-dw-u-id="{{post.authorId}}">Kitty overlord</span> </div> <div class="dw-p-bd"> <p>{{post.text}}</p> </div> </div> 我有类似的问题,可能对你有用:AngularJS – Getting data inserted in dom (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |