2

请参阅下面的示例和发送函数中的 TODO:如何将全局发送函数中的标签值分配给 dropboxController dropbox.label

<!DOCTYPE html>
<html>
  <head>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.0-beta.4/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script type="text/javascript">

      window.onload=function() { 
        $('#AddIn').append("<div ng-app='dropboxApp' ng-controller='dropboxController as dropbox'>{{dropbox.label}}</div>");
        angular.module('dropboxApp', [])
                .controller('dropboxController', function () {
                    var dropbox = this;
                    dropbox.label = "hello angular";
                });
        angular.bootstrap($('#AddIn'), ['dropboxApp']);
      }

      function send(label)
      {
        //TODO assign label value to dropboxController dropbox.label
      }
      </script>
  </head>
  <body>
    <div id="AddIn"></div>
    <button onclick="send('new label');">Send</button>
  </body>
</html>
4

1 回答 1

1

使用angular.element并获取特定 dom 元素的范围并对其应用标签。

因为dropbox.label$scope.label注入$scope控制器this不同$scope在 AngularJS 控制器中检查'this' 与 $scope

请记住:这里我使用myDiv了具有范围并在div 行angular中添加了 id 的内容。append

如果可能的话,最好使用ng-click而不是。onclick

window.onload = function() {
  $('#AddIn').append("<div id='myDiv' ng-app='dropboxApp' ng-controller='dropboxController as dropbox'>{{label}}</div>");
  angular.module('dropboxApp', [])
    .controller('dropboxController', function($scope) {
      var dropbox = this;
      $scope.label = "hello angular";
    });
  angular.bootstrap($('#AddIn'), ['dropboxApp']);
}

function send(label) {
  var scope = angular.element($("#myDiv")).scope();
  scope.$apply(function() {
    scope.label = label;
  })
  console.log(scope.label);
}
<!DOCTYPE html>
<html>

<head>
  <script src="http://apps.bdimg.com/libs/angular.js/1.4.0-beta.4/angular.min.js"></script>
  <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>

<body>
  <div id="AddIn"></div>
  <button id="myButton" onclick="send('new label');">Send</button>
</body>

</html>

于 2015-10-27T11:49:24.013 回答