AngularJS - 限制元素内的ng-init

时间:2017-05-03 17:39:47

标签: angularjs

是否可以限制在元素中使用ng-init创建的变量而不能被其他元素访问?

请查看以下示例。

预期结果: 点击myVal值旁边的按钮,只应更改同一myVal

<div>的值

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <div ng-init="myVal = 1">
    {{myVal}}
    <button ng-click="myVal = myVal+1">Adds 1</button>
  </div>
  
  <div ng-init="myVal = 1">
    {{myVal}}
    <button ng-click="myVal = myVal+1">Adds 1</button>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

是的,您可以使用 two separate controllers 进行操作,这会将范围保存在两个div中,

<强>样本

&#13;
&#13;
var app = angular.module("myApp", []);
app.controller("myCtrl1", function($scope) {
 
});
app.controller("myCtrl2", function($scope) {
 
});
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body ng-app="myApp">
   <div  ng-controller="myCtrl1" ng-init="myVal = 1">
    {{myVal}}
    <button ng-click="myVal = myVal+1">Adds 1</button>
  </div>
  
  <div  ng-controller="myCtrl2" ng-init="myVal = 1">
    {{myVal}}
    <button ng-click="myVal = myVal+1">Adds 1</button>
  </div>
</body>

</html>
&#13;
&#13;
&#13;