无法使用此方法修改范围属性

时间:2016-11-09 17:26:08

标签: angularjs model-view-controller angularjs-scope

我有一个动态加载的控制器:

var cognitosync = new AWS.CognitoSync();
cognitosync.listRecords({
            DatasetName: config.COGNITO_USERS_DATASET,
            IdentityId: identity_id,
            IdentityPoolId: config.COGNITO_IDENTITY_POOL_ID
        }, function (err, data) {

            if (err) {
               console.log("Cognito Error: ", err);
            }

            var identity_records = {};

            data.Records.forEach(function (item) {
                if (item) {
                    identity_records[item.Key] = item.Value;
                }
            });              

        });

并且1个视图延迟加载一个调用两次error: { [UnrecognizedClientException: The security token included in the request is invalid.] message: 'The security token included in the request is invalid.', code: 'UnrecognizedClientException', time: Wed Nov 09 2016 17:07:10 GMT+0000 (UTC), requestId: '1b2550a8-a69f-11e6-8c97-37b2029bd20b', statusCode: 403, retryable: false, retryDelay: 93.38622682262212 } 的模态框。

点击包含(function() { "use strict"; APP.loadController("dynamicDemoController", dynamicDemoController); dynamicDemoController.$inject = ["NgTableParams", "$scope"]; function dynamicDemoController(NgTableParams, $scope) { var self = this; self.A = 'hello'; self.edit = function(){ self.A = 'edit'; }; self.printIt = function(){ alert(self.A); // <-- print the old value 'hello', why? }; } })(); 的视图上的按钮不会更改A值。我做错了什么?

1 个答案:

答案 0 :(得分:0)

  <div ng-controller="dynamicDemoController as demo">
    {{demo.A}}
    <button ng-click="demo.edit()">edit</button>
  </div>

  <div ng-controller="dynamicDemoController as demo">
    {{demo.A}}
    <button ng-click="demo.printIt()">print</button>
  </div>

在这种情况下,控制器被重新初始化,即它再次被实例化,因为你将A变量设置为hello,它将打印为地狱。实际上它不共享变量。为了解决这个问题,请为两个按钮配置一个通用控制器,这样变量就会很常见,并且只要你想要在控制器和范围内就可以更改。

确保你打电话如下,

<body ng-app='PA' ng-controller="dynamicDemoController as demo">
   {{demo.A}}
   <button ng-click="demo.edit()">edit</button>
   <button ng-click="demo.printIt()">print</button>
</body>

这里工作正常

<强> DEMO