angular动态渲染问题

来源:互联网 发布:openbugs软件 编辑:程序博客网 时间:2024/06/05 10:26

使用angular的时候,注入双向绑定这些特性用的很爽,但其中也有一些要注意的坑,比如说这几天我在使用公司用angular写成的组件时,遇到了问题,我打算用http.get从后台动态获取数据,然后再动态生成元素,然而,,他无法动态编译,,组件未渲染,这就很尴尬了。。以下是有问题的demo:

<body ng-app="myapp" ng-controller="myctrl" ><div id="mainform"><y-input a-icon="cloud" a-max-length="10" a-value="55555" id="zujian1"></y-input></div></body><script>var myapp = angular.module("myapp",['yDataEntry','yDataDisplay','yFeedback','yun.feedback','yLayout','yNavigation']    );myapp.controller('myctrl',function($scope) {$.get('/getOne?formId=1', function (response) {        if (response.result == 'success') {            if (response.msg.jsonContent != '') {               $('#mainform').append(' <y-input a-icon="cloud" a-max-length="10" a-value="55555" id="zujian1"></y-input>')            }        }else{            alert(response.msg+'\n请先登录对应账号!')        }    });});</script>

最后的页面效果是这样的:

这里写图片描述

动态加入的组件无法渲染。。苦思无解,遂上Stack Overflow求助,,大神一下子就指出了,,你要重新编译,而且,使用angular的时候,最好不要使用jquery,这是个很不好的习惯。。。2333,附上解决代码:

var myapp = angular.module("myapp", ['yDataEntry', 'yDataDisplay', 'yFeedback', 'yun.feedback', 'yLayout', 'yNavigation']);    myapp.controller('myctrl', function ($scope, $http, $compile) {        $http({            method: 'GET',            url: '/lab/form/base/getOne?formId=1'        }).then(function successCallback(response) {            // 请求成功执行代码            debugger            if (response.data.result == 'success') {                if (response.data.msg.jsonContent != '') {                    var elm = $compile(' <y-date-picker a-format="yyyy-MM-dd" a-value="date"></y-date-picker>')($scope);                    $('#mainform').append(elm)                }            } else {                alert(response.data.msg + '\n请先登录对应账号!')            }        }, function errorCallback(response) {            // 请求失败执行代码            alert("error!")        });    });

成功!!兴奋!!

var elm = $compile(' <y-date-picker a-format="yyyy-MM-dd" a-value="date"></y-date-picker>')($scope);

感谢stackoverflow大神,顺便附上我stackoverflow求救的地址:https://stackoverflow.com/questions/45641043/angularjs-rerender-custom-compoments