angularjs 无法访问视图中的范围变量

aiqt4smr  于 2023-05-16  发布在  Angular
关注(0)|答案(5)|浏览(143)

我是Angular的新手。我无法访问视图中的范围变量。

控制器

$scope.getData = function (val) {   
      alert(val)  
      $scope.value= val;
  }

查看

<pre>{{value}}</pre>
fjaof16o

fjaof16o1#

定义

$scope.values = {thisValue:value}

然后int html

{{values.thisValue}}
vyu0f0g1

vyu0f0g12#

https://jsfiddle.net/robert07ravikumar/m3n450h1/

角代码

function MyController($scope) {
    $scope.printName = function(name) {
       $scope.namePrint = name;
    };
}

HTML代码

<div class="well" ng-controller="MyController">

    <button ng-click="printName('robert ravikumar')">print name</button>

    <span>{{namePrint}}</span>
    </div>

将值赋给范围变量(namePrint)并使用范围变量双括号在视图中显示它

gpnt7bae

gpnt7bae3#

同样的代码工作**DEMO**
你可以使用ng-bind-html-unsafe指令来绑定html数据。

<div ng-controller="MyCtrl">
    <pre ng-bind-html-unsafe="value"></pre>
</div>

DEMO

w80xi6nr

w80xi6nr4#

HTML

<div ng-app="myApp" ng-controller="myCtrl">

    <div class="row">
        <div class="col-lg-2"><input type="text" ng-model="value" /></div>
        <div class="col-lg-2"> <input type="button"  value="GetData " ng-click="GetData('myNewValueProvidedFromHtml')" /></div>

    </div>

  <span ng-bind="value"></span>
</div>

Angular

var myApp = angular.module("myApp", []);

myApp.controller('myCtrl', function ($scope) {

    $scope.value = "my value";

    $scope.GetData = function (newValue) {
        $scope.value = newValue;

    }

});
0h4hbjxa

0h4hbjxa5#

您需要调用$scope.$digest()来告诉angular重新处理视图。即:

$scope.getData = function (val) {   
  alert(val)  
  $scope.value= val;
  $scope.$digest();
}

相关问题