访问ng-if中的$ scope

时间:2016-07-13 17:21:10

标签: angularjs angular-ng-if

在我的指令(没有$ parent.params.text)中访问由ng-if创建的作用域的更好方法是什么:

<span ng-if="params" uib-tooltip="{{params.text}}"></span>

.directive('myDirective', functions(){
   return {
      templateUrl: 'template.html',
      replace: true,
      $scope: {
         data: '='
      },
      controller: function(){
          if (data) { //some logic
             $scope.params.text = 'text'
          }
      }
   }
})

2 个答案:

答案 0 :(得分:2)

我注意到如果我的变量嵌套在对象中,我就不必使用$parent

例如:

<强>控制器 $scope.params = { ... }

查看 ng-if="params"

不会工作,但是:

<强>控制器

$scope.something_here = {};
$scope.something_here.params = { ... }

查看 ng-if="something_here.params"

工作。我相信,如果您尝试访问的密钥是对象的一部分,Angular会保留范围。试一试!

答案 1 :(得分:0)

您可以使用controllerAs语法。

添加

controllerAs: "vm",
bindToController: true

作为指令定义中的属性,并用vm替换$ scope。 然后参考ng-if

中的vm.params.text
相关问题