2016-03-23 99 views
0

我正在使用角度单向绑定从控制器到指令。当我更新指令中的值时,它不应该更新控制器中的值。但它是以双向约束的方式工作的。有人能找到我的错误。角度指令单向绑定更改控制器中的值

angular.module("myApp",[]) 
    .directive("myDirective",['$timeout', function ($timeout) { 
    return { 
     scope: {myValue: "&myAttribute"}, 
     template: '<input type="text" ng-model="myValue().name">', 
     link: function (scope, iElm, iAttrs) { 
     var x = scope.myValue(); 
     console.log(x); 
     $timeout(function(){ 
      x.name= "directive"; 
     },4000); 
     } 
    }; 
    }]).controller("myController", function ($scope, $timeout) { 
    $scope.someObject = {name: "test"}; 
    $timeout(function(){ 
     $scope.someObject.name= "controller"; 
    },2000); 

}); 

http://plnkr.co/edit/9wihx1VYgKoTK00awN67?p=preview

+1

我认为,符号是要创建一个返回父范围someObject的值的函数,https://docs.angularjs.org/api/ng/service/$编译,所以这不是单向的。 – ryansstack

+0

是的,并返回一个getter函数。所以它应该是单向的 –

+1

虽然它获取对象的引用,所以指令和父范围都具有相同的引用,并且对对象属性的任何更改都将自然显示在两个位置 – ryansstack

回答

1

按照文档使用 “@”,而不是 “&”(为1.xx)https://docs.angularjs.org/api/ng/service/ $ compile&amp;将返回在父范围(getter)中执行的属性表达式的值,在这种情况下,它是对象引用,并且对任何对象属性的更改都将反映在两者中。

但是,指令作用域中myValue的更改不会影响父作用域。

1

我不确定是否有更简单的方法,但您可以使用单向绑定与@绑定在隔离范围内,并在属性上添加观察者以更新指令中对象的更改。

@绑定从父级获取数据并将它们作为字符串传递给指令。要创建一个对象,您必须使用scope.$eval(interpolatedStrValue)

(与号绑定,在其他答复中提到,因为吸气剂是通过基准父对象无法正常工作。因此,任何改变都会更新父也。)

请看看的演示如下或在此fiddle

angular.module('demoApp', []) 
 
\t .directive('oneWay', OneWay) 
 
    .controller('mainController', MainController); 
 
    
 

 
function OneWay($timeout, $parse) { 
 
\t return { 
 
    \t scope: { 
 
    \t myValue: '@myAttribute' 
 
    }, 
 
    \t template: '<input type="text" ng-model="myValue.name"/>', 
 
    link: function(scope, element, attrs) { 
 
    \t console.log('link', scope.myValue); 
 
     attrs.$observe('myAttribute', function(myValStr) { 
 
     \t scope.myValue = scope.$eval(myValStr); 
 
     console.log('controller myValue obj', scope.myValue); 
 
     }); 
 
     
 
     $timeout(function() { 
 
     \t console.log('change dir'); 
 
     scope.myValue.name = "directive changed"; 
 
     }, 4000); 
 
     
 
     
 
    } 
 
    } 
 
} 
 

 
function MainController($scope, $timeout) { 
 
\t $scope.testObj = { 
 
    \t name: 'before mod.' 
 
    }; 
 
    
 
    $timeout(function() { 
 
    \t $scope.testObj.name = 'Controller modify'; 
 
    }, 2000); 
 
    
 
    $timeout(function() { 
 
    \t $scope.testObj.name = '2nd Controller modify'; 
 
    }, 8000); 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.js"></script> 
 
<div ng-app="demoApp" ng-controller="mainController"> 
 
    Controller: {{testObj.name}}<br/> 
 
    Directive: <one-way my-attribute="{{testObj}}"/> 
 
</div>

相关问题