【问题标题】:Angular directive - update parent scope when another directive as also isolated scopeAngular 指令 - 当另一个指令也作为隔离范围时更新父范围
【发布时间】:2014-04-01 04:18:00
【问题描述】:

我编写了一个需要更新父作用域的角度指令。

angular.module('app').directive('googlePlace', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function ($scope, element, attributes, model) {

              $scope.property1 = 'some val';
              $scope.property2 = 'another val'; 
              $scope.$apply();

    };
});

但在我的控制器中我这样做:

MyCtrl = function($scope){
$scope.doSave = function(){
   // do some logic
   console.log($scope.property1);
   console.log($scope.property2);


}

}

doSave 运行时,我的控制台中出现未定义的值。如何在不隔离范围的情况下将其应用于父范围。我没有这个选项,因为同一元素上的另一个指令隔离了范围。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    它应该工作。默认情况下,如果您未在指令中指定范围,则它使用父范围,因此应设置 property1 和 property2。尝试将指令中的范围设置为 false。附带说明一下,您正在做的事情不是一个好习惯。最好隔离范围并将属性添加为属性。这样您将获得良好的封装。

    例如

    angular.module('app').directive('googlePlace', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                property1: '=',
                property2: '='
            }
            link: function ($scope, element, attributes, model) {
    
                //here you have access to property 1 and 2
    
        };
    });
    
    function MyCtrl($scope) {
        $scope.property1 = null;
        $scope.property2 = null;
    
        $scope.doSave = function(){
       // do some logic
           console.log($scope.property1);
           console.log($scope.property2);
        }
    }
    

    还有你的html

    <div ng-control="MyCtrl">
    <div google-place property1='property1' property2='property2'></div>
    </div>
    

    【讨论】:

      【解决方案2】:

      我不知道你做错了什么,因为它似乎工作:http://jsfiddle.net/HB7LU/2865/

      var myApp = angular.module('myApp',[]);
      angular.module('myApp').directive('googlePlace', function () {
          return {
              restrict: 'A',
              require: 'ngModel',
              link: function ($scope, element, attributes, model) {
      
                    $scope.property1 = 'some val';
                    $scope.property2 = 'another val'; 
                    $scope.$apply();
      
          }
      }
      });
      
          angular.module('myApp').controller('MyCtrl', MyCtrl);
      //myApp.directive('myDirective', function() {});
      //myApp.factory('myService', function() {});
      
      function MyCtrl($scope) {
          $scope.doSave = function(){
         // do some logic
         console.log($scope.property1);
         console.log($scope.property2);
      
      
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多