javascript - 如何从内部指令更改 Controller 的 $scope 属性?

标签 javascript angularjs angularjs-directive

我的 View 中有一个按钮,它完全在 View 中处理,因为它只是一个使用 ng-show 指令切换元素 View 的简单开关。我希望能够从指令内部切换 View 。

这是我正在尝试执行的示例代码:

<div>
<button ng-click="ToChange=true">
<my-directive ng-show="ToChange"></my-directive>
</div>

  .directive('myDirective', function() {
  return {
    ...
    controller: function ($scope) {
      $scope.whenClickedThis = $scope.ToChange=false ???
    },
    ...
  };
});

最佳答案

在您的 Angular Directive(指令)中,您可以访问父范围或隔离范围。如果您计划使用父作用域,那么

angular.module('app')
.controller('mainController', function($scope){
    $scope.ToChange = false;
})
.directive('myDirective', function(){
    return {
        restrict: 'E',
        controller: function($scope){
            //You can access $scope.ToChange here
        }),
        link : function($scope, $element, $attribute){
            //You can access $scope.ToChange here
        }
    }
});

<div ng-controller="mainController">
    <button ng-click="ToChange=true">
    <my-directive ng-show="ToChange"></my-directive>
</div>

如果您计划为指令创建隔离范围,

angular.module('app')
.controller('mainController', function($scope){
    $scope.ToChange = false;
})
.directive('myDirective', function(){
    return {
        restrict: 'E',
        scope : {
            change : '='
        },
        controller: function($scope){
            //Now you can access $scope.change from here
        }),
        link : function($scope, $element, $attribute){
            //Now you can access $scope.change from here
        }
    }
});

<div ng-controller="mainController">
    <button ng-click="ToChange=true">
    <my-directive change="ToChange"></my-directive>
</div>

如果您想识别变量的任何更改,可以在指令中创建监视

$scope.$watch('change', function(oldValue, newValue) {
    //Do something here;
});

了解有关 Angular 范围的更多信息 here

关于javascript - 如何从内部指令更改 Controller 的 $scope 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44540009/

相关文章:

javascript - Angularjs 自定义指令范围 :true change it's parent scope

angularjs - 设置来自 AngularJS 指令的多个输入的有效性

javascript - Angularjs UI-Router : How to create view inside nested view?(3层嵌套 View )

angularjs - 使用 Angular JS ng-csp 指令构建特权 Firefox OS 应用程序

javascript - 在我的 Angular Controller 中调试 promise ,如果错误消息中没有文件名和 lineno,则非常困难

javascript - d3 补间弧在函数调用中不起作用

angularjs - 如何根据 bootstrap 网格系统使用 angularjs 指令设置 height = width 以获得方形 div?

javascript - 如何在 Jint 中枚举字典<>

javascript - 单击外部 div 以关闭 div

javascript - 从 JS 嵌套模型中 knockout JS 映射