2016-01-19 34 views
0

我也是新的AngularJS,並且有一個簡單的問題。將範圍值保存在另一個範圍內並同時顯示

我想將<input type="text" ng-model="abc">的值存儲到另一個名爲$scope.cde的作用域中,並同時顯示它們。此時只顯示{{ abc }},但不顯示{{ cde }}

爲什麼這不適用於此代碼? plnkr

HTML:

<!DOCTYPE html> 
<html ng-app="myApp"> 

    <head> 
    <script data-require="[email protected]" data-semver="1.2.7" src="http://code.angularjs.org/1.2.7/angular.js"></script> 
    <script src="script.js"></script> 
    </head> 
    <body > 
    <div ng-controller="ExampleCtrl"> 
     <h2>Scope Example</h2> 
     <input type="text" ng-model="abc"> 
     <p>{{ abc }}</p> 
     <p>{{ cde }}</p> 
    </div> 
    </body> 

</html> 

JS:

var myApp = angular.module('myApp', []); 

myApp.controller('ExampleCtrl', function ($scope) { 

    $scope.cde = $scope.abc; 

}); 
+2

安德里的答案是正確的,只是,我會做一個函數賦值。 'ng-change = assignValue()'然後'assignValue'就是'$ scope.cde = $ scope.abc' – frishi

+0

@frishi謝謝,正是我在找的東西。 – herrh

回答

4

使用ng-change做到這一點

<input type="text" ng-model="abc" ng-change='cde = abc'> 
+1

更新工作plunker - http://plnkr.co/edit/VaklHZ3klatsSiZWtxjs?p=preview – nikhil

+1

http://plnkr.co/edit/7QElHM?p=preview剛剛作出了一個plunker與我的建議。 – frishi

0

您可以使用指令隔離範圍,如果你想:

HTML

<body > 
<div ng-controller="ExampleCtrl"> 
    <h2>Scope Example</h2> 
    <input type="text" ng-model="abc" placeholder="enter stuff here" x-change:scope="cde"> 
    <p><strong>abc scope:</strong> {{ abc }}</p> 
    <p><strong>cde scope:</strong> {{ cde }}</p> 
</div> 
</body> 

JS

myApp.directive('changeScope', function() { 

    var controller = ['$scope', function ($scope) { 
    $scope.setValue= function(abc){ 
     $scope.cde = abc; 
    } 
    }]; 

    var component = function(scope, element, attrs) {  
    scope.$watch('abc', function (v) { 
     scope.setValue(v); 
    }); 
    } 

    return { 
    link:  component, 
    controller: controller, 
    // Isolated scope 
    scope: { 
     abc: '=ngModel', 
     cde: '=changeScope' 
    } 
    }; 

}); 

檢查working plnkr

相關問題