get access to $scope in ng-if

不羁岁月 提交于 2020-01-07 02:22:25

问题


What is the better approach to get access to scope created by ng-if in my directive (without $parent.params.text):

<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'
          }
      }
   }
})

回答1:


I've noticed that I don't have to use $parent if my variable is nested inside an object.

For example:

controller $scope.params = { ... }

view ng-if="params"

Won't work, but:

controller

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

view ng-if="something_here.params"

would work. I believe Angular preserves the scope if the key you're trying to access is part of an object. Give it a try!




回答2:


You could use the controllerAs syntax.

add

controllerAs: "vm",
bindToController: true

as properties in your directive definition and replace $scope with vm. Then refer to vm.params.text inside the ng-if



来源:https://stackoverflow.com/questions/38358042/get-access-to-scope-in-ng-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!