【问题标题】:How I can know directive has been completely compiled in angularjs我怎么知道指令已经在 angularjs 中完全编译
【发布时间】:2016-01-04 06:51:22
【问题描述】:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <title>test directive</title>
</head>
<body ng-controller="bodyController">

  <hello alert="outAlert"></hello>

  <script type="text/javascript" src="http://cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
  <script type="text/javascript">
  angular.module("myApp", [])

  .directive("hello", function(){
    return {
      scope: {
        alert: "="
      },
      link: function(scope, elem, attrs){
        scope.alert = function(msg){
          window.alert(msg)
        }
      }
    }
  })

  .controller("bodyController", function($scope, $timeout){
    $scope.outAlert("this occurs an error: undefined is not a function")

    $timeout(function(){
      $scope.outAlert("this works great!")
    }, 100)
  })
  </script>
</body>
</html>

如上代码,hello 指令将outAlert 函数传递给bodyController。但是bodyController不能立即使用outAlert,否则会出现“undefined is not a function”的错误。

所以我必须在 100 毫秒后运行它。但它看起来不像一个正式的解决方案。我想寻求更好的方法!

我怎么知道指令已经完全编译在 angularjs 中???

【问题讨论】:

  • 您正在重新定义传递给 link 内指令的警报。没有意义。创建一个包含基本 html 并复制您的问题的演示。你的控制器不能使用其中定义的函数也没有任何意义,除非你正在覆盖它,如果它也被传递到链接中
  • 你想用这个来完成什么?我认为您应该使用$on$emit 的自定义范围事件,而不是尝试与函数对象进行双向绑定。

标签: angularjs directive compiled


【解决方案1】:

经过我这几个月的实践,最好在指令中提供一个回调给外部组件,因为如果它调用自己提供的回调,指令必须完全编译。

(我的英语很差!你听得懂吗?)

【讨论】:

    猜你喜欢
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多