質問

I have the following view in my code:

<div data-ng-controller="HelloCtrl">
    {{counties.selected}}
</div>   

This piece of code will update the html successfully (when $scope.counties.selected is set to a string:

$scope.$watch('counties.selected', function(newValue, oldValue) {
   $scope.counties.selected = 'string';
});

However, the html doesn't update when $scope.counties.selected is set to a variable as below. console.log(newValue); show that newValue has the expected value set:

$scope.$watch('counties.selected', function(newValue, oldValue) {
   console.log(newValue);
   $scope.counties.selected = newValue;

});

Why doesn't newValue propagate to the html?

役に立ちましたか?

解決 2

I would use a factory to pass data between the two controllers. We can inject the CountiesFactory into both the controllers as a dependency injection, and modifying the object in one controller will affect the values in the other controller.

http://jsfiddle.net/t5x8j/

JS

angular.module('testApp', [])
.controller('MyFirstCtrl', function($scope, CountiesFactory) {
    $scope.temp = CountiesFactory;
})
.controller('MySecondCtrl', function($scope, CountiesFactory) {
    $scope.counties = CountiesFactory;
})
.factory('CountiesFactory', function() {
    return {
        options: [
            {
                text: 'blah blah',
                value: 1
            },
            {
                text: 'meh meh',
                value: 2
            }            
        ]
    }
})

HTML

<body ng-app='testApp'>
    <div ng-controller='MyFirstCtrl'>
        <select ng-model='temp.selected' ng-options='option.text for option in temp.options'></select>
    </div>

    <div ng-controller='MySecondCtrl'>
        {{ counties.selected }}
    </div>


</body>

他のヒント

You do not need to $watch this value. It will be updated automatically.

http://plnkr.co/edit/0HEJEBWbYMGU4bUrAcm0?p=preview

Here is working example with watcher, but this $watch is there excess.

http://plnkr.co/edit/f21n0bvPHU8ILQpW8M78?p=preview

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top