通过 ng-init 将变量注入到控制器

2024-03-19

我想将具有不同值的相同变量多次注入到同一个控制器中。这就是我尝试过的。在每次调用中获取不同值的方法是什么?

HTML

<body ng-app="myApp">
    <div ng-controller="myCtrl" ng-init="test='helloworld';test1='helloworld2'">

    </div>
    <div ng-controller="myCtrl" ng-init="test='helloworld3';test1='helloworld4'">

    </div>
    <div ng-controller="myCtrl" ng-init="test='helloworld5';test1='helloworld6'">

    </div>
<body>

JavaScript 代码

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

app.controller("myCtrl", ["$scope",function($scope) {
    console.log($scope.test);
    console.log($scope.test1);
}]);

ng-init文件说:

该指令可能被滥用以添加不必要的逻辑量 你的模板。 ngInit 只有几种合适的用途,例如 至于 ngRepeat 的特殊属性别名,如演示中所示 以下;以及通过服务器端脚本注入数据。除了这些 少数情况下,您应该使用控制器而不是 ngInit 来初始化 范围内的值。

您不应该使用分配初始值ng-init。正确的方法是在 AngularJS 的末尾进行赋值controller功能。

从技术上讲,发生的事情是ng-init指令在之后被评估ng-controller函数被注册。这就是为什么初始化值来自ng-init在控制器内部不可用。

基本上,背后的原因ng-controller首先接到电话是优先事项。如果你看一下priority, the ng-init指令有450& 这priority指令的选项,其中ng-controller指令有500,同时从 DOM 编译指令AngularJS http://en.wikipedia.org/wiki/AngularJS根据优先级对它们进行排序。因此ng-controller首先被执行。

Code

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

app.controller("myCtrl", ["$scope",function($scope) {
    console.log(test);
    console.log(test1);

    // If you wanted to assign the values dynamically you could make Ajax here
    // that would call the server-side method which will return the values
    // and in success that Ajax you could set those scope values.
    // If any dependent function should get called after assigning them.
    // Then you can call that function from that Ajax success.
    $http.get('/getDefaultValues').then(function(response){
        var data = response.data;
        $scope.test= data.value1;
        $scope.test1 = data.value2;
    });
}]);

Edit

看来上面的代码是不可能执行的,因为变量值是从jsp/aspx页。出于这个原因,我建议采用另一种方法来实现这一目标。我认为这是更干净的方式。

我建议您使用以下方式延迟初始化您的角度应用程序angular.bootstrap而不是使用ng-app页面加载后立即初始化应用程序。

angular.element(document).ready(function() {
  angular.bootstrap(document, ['TodoApp']);
});

现在您会想,在使控制器可用之前如何解决将变量分配给作用域的问题,在这种情况下,您可以创建一个值对象并分配正在填充的变量jsp/aspx页面value(服务种类)

<script type="text/javascript">
    angular.element(document).ready(function() {
      //like below you could get value inside your app by assigning
      //to some angular component like constant/value
      angular.module('TodoApp').value('sharedData', {
          'test': @myValueFromAspxPage,
          'test1': @myValueFromAspxPage1
      });
      angular.bootstrap(document, ['TodoApp']);
    });
</script>

通过执行上述操作,您可以轻松地在控制器内提供您的值,然后无需等到一个摘要周期完成使用$timeout。您可以在里面使用这个值注入sharedData通过注入控制器内部来获取值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 ng-init 将变量注入到控制器 的相关文章

随机推荐