虽然范围变量在angularjs中已更改,但视图不会更改

时间:2016-07-15 10:59:39

标签: angularjs view scope

我整天坚持这一点。

<table>
    <tr ng-repeat="x in usernames">
        <td>{{x.username}}</td>
        <td>
            <button type='button' ng-click='sendMessage()'>Send  Message</button>
        </td>
        <td>
            <button type="button" ng-click="deleteUser()">Delete User</button>
        </td>
    </tr>
</table>

当我按“发送消息”时,控制器会成功点亮。

$scope.sendMessage = function () {
    $scope.content_in = '<form novalidate>'
        +'<label>Message: &nbsp</label> <input type="text" ng-model="message"/><br><br>'
        +'<button id="mybutton" style="width:75px" ng-click="send()">Send</button>'
        +'<input id="mycancel" style="width:75px" type="reset" value="Cancel"/>'
        +'</form>';
}

我只是尝试使用消息表单更新我的页面,该表单将放在content_in变量中。但这些变化并未反映在视图中。

我还包括:

$scope.$watch('content_in', function () {
    alert('hey, content_in has changed!');
});

在控制器中,我确信更改是在控制器中进行的。 如何让视图反映更改?

1 个答案:

答案 0 :(得分:1)

尝试以下方法

 myApp.controller("myController", function ($scope,  $compile, myService) 
{
    $scope.sendMessage = function () {
        var content_in = '<form novalidate>'
        +'<label>Message: &nbsp</label> <input type="text" ng-model="message" /><br><br>'
        +'<button id="mybutton" style="width:75px" ng-click="send()">Send</button>'
        +'<input id="mycancel" style="width:75px" type="reset" value="Cancel" />'
        +'</form>';
        var element = angular.element(document.querySelector("#myDiv"));
        element.empty();
        element.append(content_in);
        $compile(element.contents())($scope);
    }
});

在您的设计页面中添加此div

<div id="myDiv">