2014-03-30 45 views
5

我寫了一個需要更新父範圍的角度指令。Angular指令 - 當另一個指令也是隔離範圍時更新父範圍

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運行,我在我的控制檯獲得未定義的值。如何在不隔離範圍的情況下將其應用於家長範圍。我沒有這個選項,因爲同一元素上的另一個指令隔離範圍。

回答

3

它應該工作。默認情況下,如果您不在指令中指定範圍,則它使用父級作用域,因此應設置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> 
1

我不知道你在做什麼錯誤的,因爲它似乎工作: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); 


} 
}